-
-
Save Oliver-ke/6e98b095716a8ff6bec011eb5a2ec17d to your computer and use it in GitHub Desktop.
Testing stateful React hooks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState } from 'react'; | |
export function useCounter(initial = 0) { | |
const [count, setCount] = useState(initial); | |
return [count, () => setCount(count + 1)]; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useCounter } from './Calculator'; | |
const mockSetState = jest.fn(); | |
jest.mock('react', () => ({ | |
useState: initial => [initial, mockSetState] | |
})); | |
test('Can increment from 1 to 2', () => { | |
const [_, increment] = useCounter(1); | |
increment(); | |
expect(mockSetState).toHaveBeenCalledWith(2); | |
}); |
more examples
import React, { useState as useStateMock } from 'react';
jest.mock('react', () => ({
...jest.requireActual('react'),
useState: jest.fn(),
}));
describe('testing useState mocked', () => {
const setState = jest.fn();
const useStateMock = (initState: any) => [initState, setState];
jest.spyOn(React, 'useState').mockImplementation(useStateMock);
afterEach(() => {
jest.clearAllMocks();
});
// your tests goes here
});
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Mocking useState in a component with using useState