This cheatsheet uses the following stack
import React from 'react';
import { shallow } from 'enzyme';
import renderer from 'react-test-renderer'; // for jest snapshot
import toJson from 'enzyme-to-json'; // for enzyme snapshot
const wrapper = shallow(<SomeComponent />);
//mock event if event is accessed
const event = { preventDefault: jest.fn() };
wrapper.find('button').simulate('click', event);
expect(event.preventDefault.mock.calls.length).toBe(1);
const wrapper = shallow(<SomeComponent />);
const event = { target: { value: 'user123' } };
wrapper.find(`input[name='username']`).simulate('change', event);
const wrapper = shallow(<SomeComponent />);
expect(wrapper.find('ChildElementOrComponent').length).toBe(1);
//attribute selector
expect(wrapper.find(`input[type='submit']`).length).toBe(1);
const wrapper = mount(<SomeComponent />);
const element = wrapper.instance().componentInstanceVariableHoldingTheRef;
spyOn(element, 'focus');
// call code that triggers focus
// ...
expect(element.focus).toHaveBeenCalledTimes(1);
// foosModule.js
export const foo = () => {...}
// fooConsumerModule.js
import { foo } from './foosModule.js';
export const fooConsumer = () => foo();
// test.js
import fooConsumer from './fooConsumerModule.js';
// import and mock the implementation
const module = require('./foosModule.js');
module.foo = () => 42;
expect(fooConsumer()).toEqual(42);
jest.mock('./foo');
const foo = require('./foo');
foo.mockImplementation(() => 42);
//mock the function
const propFunction = jest.fn();
const wrapper = shallow(<SomeComponent propFunction={propFunction} />);
//propFunction was called once
expect(propFunction.mock.calls.length).toBe(1);
//propFunction was called with argument 'arg'
expect(propFunction.mock.calls[0][0]).toEqual(arg);
wrapper.setProps({ name: 'bar' });
http://airbnb.io/enzyme/docs/api/ShallowWrapper/setProps.html
const wrapper = shallow(<SomeComponent />);
wrapper.instance().componentFunction();
const state = { ... };
const expectedState = { ... };
const payload = { ... };
const action = actionCreator(payload);
expect(reducer(state, action).toEqual(expectedState);
const wrapper = shallow(<Component {...props}></Component>);
expect(toJson(wrapper)).toMatchSnapshot();
const tree = renderer.create(<Component {...props}/>).toJSON();
expect(tree).toMatchSnapshot();
const wrapper = shallow(<SomeComponent />);
expect(wrapper.state().fruit).toEqual('apple');
test('', done => {
const wrapper = shallow(<SomeComponent />);
// do something that changes state in an async method
process.nextTick(() => {
wrapper.update();
expect(wrapper.state().fruit).toEqual('apple');
done();
});
});
const wrapper = shallow(<SomeComponent />);
wrapper.instance().setState({fruit: 'orange'}));
setInterval(() => this.setState({ flag: true }), 100);
jest.useFakeTimers();
test('', () => {
jest.runTimersToTime(100);
wrapper.update();
expect(wrapper.state().flag).toEqual(true);
});