How to set initial state for useState Hook in jest and enzyme?

You can mock React.useState to return a different initial state in your tests: // Cache original functionality const realUseState = React.useState // Stub the initial state const stubInitialState = [‘stub data’] // Mock useState before rendering your component jest .spyOn(React, ‘useState’) .mockImplementationOnce(() => realUseState(stubInitialState)) Reference: https://dev.to/theactualgivens/testing-react-hook-state-changes-2oga

How can I use Jest to spy on a method call?

The key is using jests spyOn method on the object’s prototype. It should be like this: const spy = jest.spyOn(Component.prototype, ‘methodName’); const wrapper = mount(<Component {…props} />); wrapper.instance().methodName(); expect(spy).toHaveBeenCalled(); As found here e.g.: Test if function is called react and enzyme Please note it is also best practice to clear the spied function after each … Read more

Testing with React’s Jest and Enzyme when simulated clicks call a function that calls a promise

Updated answer: using async / await leads to cleaner code. Old code below. I’ve successfully solved this problem by combining the following elements: Mock out the promise and make it resolve immediately Make the test asynchronous by marking the test function async After simulating the click, wait until the next macrotask to give the promise … Read more

When should you use render and shallow in Enzyme / React tests?

As per the Enzyme docs: mount(<Component />) for Full DOM rendering is ideal for use cases where you have components that may interact with DOM apis, or may require the full lifecycle in order to fully test the component (ie, componentDidMount etc.) vs. shallow(<Component />) for Shallow rendering is useful to constrain yourself to testing … Read more

Simulate a button click in Jest

#1 Using Jest This is how I use the Jest mock callback function to test the click event: import React from ‘react’; import { shallow } from ‘enzyme’; import Button from ‘./Button’; describe(‘Test Button component’, () => { it(‘Test click event’, () => { const mockCallBack = jest.fn(); const button = shallow((<Button onClick={mockCallBack}>Ok!</Button>)); button.find(‘button’).simulate(‘click’); expect(mockCallBack.mock.calls.length).toEqual(1); … Read more

How to make Jest wait for all asynchronous code to finish execution before expecting an assertion

Updated for Jest 27+ For jest 27+, you can also use process.nextTick: await new Promise(process.nextTick); (Thanks to Adrian Godong in the comments) Original Answer Here’s a snippet that waits until pending Promises are resolved: const flushPromises = () => new Promise(setImmediate); Note that setImmediate is a non-standard feature (and is not expected to become standard). … Read more

tech