Skip to content

Instantly share code, notes, and snippets.

@stinaq
Last active May 16, 2018 13:22
Show Gist options
  • Save stinaq/abf77ced53867dcabe254e56d0d60a3a to your computer and use it in GitHub Desktop.
Save stinaq/abf77ced53867dcabe254e56d0d60a3a to your computer and use it in GitHub Desktop.

Testing React with Jest and Enzyme - cheatsheet

Basic

const props = { disableTooltip: disableTooltipMock };
const wrapper = shallow(<PlannerTooltip {...props} />);

See props on a component

wrapper.props()

returns an object with all the props: {children: "Hello", className: "foo bar", includedProp="Success!"}

wrapper.prop('includedProp')

returns the value in that specific prop

Mocks

Using a mock to spy on as a property to a component

const disableTooltipMock = jest.fn();
const wrapper = shallow(<PlannerTooltip onClick={disableTooltipMock} />);

it('should call disableTooltip', () => {
  expect(disableTooltipMock).toHaveBeenCalled();
});
it('should call disableTooltip with parameter Wonder Woman', () => {
  expect(disableTooltipMock).toHaveBeenCalledWith('Wonder Woman');
});
it('should call disableTooltip 2 times', () => {
  expect(disableTooltipMock).toHaveBeenCalledTimes(2);
});

Get hold of internal variables on the component

Finds everything on this in the component.

const wrapper = shallow(<PlannerTooltip />);
const instance = wrapper.instance();
expect(instance.isOpen).toEqual(false);

Call internal methods on the component

const wrapper = shallow(<PlannerTooltip />);
const instance = wrapper.instance();
instance.openModal();
expect(instance.state.isOpen).toEqual(true);

Set new props

wrapper.setProps({ activePlannerPage: 'LAYOUT' });

Trigger events

const wrapper = shallow(); wrapper.simulate('click');

Testing react events

componentWillReceiveProps

Create the component, then set props wrapper.setProps({ activePlannerPage: 'LAYOUT' });

componentDidUpdate

You must do mount instead of shallow to test componentDidUpdate. This will also run other lifecycle, for example componentWillReceiveProps

const wrapper = mount(<PlannerTooltip />);
wrapper.setProps({ activePlannerPage: 'LAYOUT' });

Time

jest.useFakeTimers();
jest.runTimersToTime(5000);
jest.useRealTimers();
@stinaq
Copy link
Author

stinaq commented May 4, 2018

Det är något irriterande med att det inte går att mocka dependencies per test.
Om man gör mock på en dependency import, och sen gör "afterEach" reset all mocks, hur funkar det??

@stinaq
Copy link
Author

stinaq commented May 16, 2018

Spy on internal method:

        instance = wrapper.instance();
        instance.updateEntities = jest.fn();
        expect(instance.takeScreenshot).not.toHaveBeenCalled();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment