Skip to content

Instantly share code, notes, and snippets.

@stinaq
Last active May 16, 2018 13:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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 Dec 22, 2017

  • simulate
  • hur man hittar med find
  • hur man vet om ett element finns eller inte

@stinaq
Copy link
Author

stinaq commented Feb 22, 2018

spyOn finns för att spionera utan att ersätta originalet jestjs/jest#3580
För det finns resetAllMocks()

@stinaq
Copy link
Author

stinaq commented Feb 22, 2018

window.matchMedia = jest.fn().mockReturnValue({ matches: 0 });

@stinaq
Copy link
Author

stinaq commented Feb 22, 2018

Om man fått ut en lista av element, med exempelvis find, så kan man använda first() för att hitta den första.
expect(images.first().prop('src').toEqual('somebase64');
Men om man vill hitta andra ska man använda get(index)
Då kan man inte göra prop('src') utan måste ist göra props.src av någon anledning
get ger en reactNode, till skilnad från at som ger en reactWrapper. Den senare kan man göra simulate

@stinaq
Copy link
Author

stinaq commented Mar 12, 2018

expect(generate).toHaveBeenCalledWith(expect.any(Object), 550, expect.any(Object));

@stinaq
Copy link
Author

stinaq commented Mar 23, 2018

Vill du spionera på en mock?

importera modulen till testfilen, import { fullpageLoader } from 'fullpageLoader';
Mocka sen ut den, där strängen är vad modulen heter

jest.mock('fullpageLoader', () => ({
  fullpageLoader: {
    end: jest.fn(),
  },
}));

Sen kan du bara göra expect(fullpageLoader.end).toHaveBeenCalledTimes(1);

@stinaq
Copy link
Author

stinaq commented Mar 26, 2018

För att mocka ut komponenter som är exporterade default:

jest.mock('ui/HeaderStandard', () => () => (<div />));

@stinaq
Copy link
Author

stinaq commented Apr 5, 2018

Mocka ut resultatet av en global, typ Math.random:
jest.spyOn(Math, 'random').mockImplementation(() => 1);

@stinaq
Copy link
Author

stinaq commented Apr 11, 2018

testing preventDefault in a simulate click

    const preventDefaultMock = jest.fn();
    includedLink.simulate('click', { preventDefault: preventDefaultMock });
    it('should call the onClick callback', () => {
      expect(onClickMock).toHaveBeenCalledTimes(1);
    });

@stinaq
Copy link
Author

stinaq commented Apr 24, 2018

debug?
wrapper.find(Box).children().debug();

@stinaq
Copy link
Author

stinaq commented May 4, 2018

om man vill skriva ut själva markupen:
http://airbnb.io/enzyme/docs/api/ReactWrapper/html.html
(wrapper.html()

@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