I try to write unit test with react component implement by typescript, but I got an error when mock some hook function.
My unit test implement:
import React from 'react';
import { useHistory } from 'react-router-dom';
import { MyComponent } from './index';
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useHistory: () => ({ replace: jest.fn() ]),
}));
describe('MyComponent', () => {
it('Should pass', () => {
// My render implementation
(useHistory as jest.Mock).mockReturnValue({ pathname: '/test' });
});
});
When I run test case it throw an error:
TypeError: _reactRouterDom.useHistory.mockReturnValue is not a function
You've assigned an anonymous function to useHistory instead of the mock function created by jest.fn(). .mockReturnValue() method exists on jest.fn(). Try:
import { useHistory } from 'react-router-dom';
jest.mock('react-router-dom', () => ({
...(jest.requireActual('react-router-dom') as object),
useHistory: jest.fn(),
}));
describe('MyComponent', () => {
test('should pass', () => {
(useHistory as jest.Mock).mockReturnValue({ location: { pathname: '/test' } });
const history = useHistory();
expect(history.location.pathname).toBe('/test');
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With