nhlinh
nhlinh

Reputation: 121

Unit test TypeError: _reactRouterDom.useHistory.mockReturnValue is not a function

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

Upvotes: 7

Views: 11721

Answers (1)

Lin Du
Lin Du

Reputation: 102267

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');
  });
});

Upvotes: 21

Related Questions