Home > Enterprise >  Mock custom hook from 3rd party library in Jest
Mock custom hook from 3rd party library in Jest

Time:12-01

I am using a custom hook from 3rd party library in my React project:

import { useProductData } from '@third/prod-data-component';

const ProductRow: React.FC<MyProduct> = ({ product }) => {
  // using the custom hook here
  const productData = useProductData();
})

The signature of that hook function is:

export declare const useProductData: () => string | undefined;

In my jest test, I would like to mock the returned value of the hook, I tried:

it('should show correct product data', ()=>{
   jest.mock('@third/prod-data-component', () => {
      return { useProductData: jest.fn(()=>'foo')}
   });
   ...
   ...
})

When I run test, the above mock doesn't take any effect.

How to mock the return value of custom hook that is from a 3rd party library?

==== UPDATE ====

I also tried this:

jest.mock('@third/prod-data-component', () => {
            const lib = jest.requireActual('@third/prod-data-component');
            return {...lib, useProductData: () => 'foo'}
        });

But does't work either.

CodePudding user response:

can you try this

import {useProductData} from '@third/prod-data-component'

jest.mock('@third/prod-data-component');

(useProductData as jest.Mock).mockImplementation(() => {mockKey: 'mockData'})

describe('test scenario', () => {
  it('should show correct product data', () => {
    // your assertions
  })
})

CodePudding user response:

Reading your example, you may be missing the actual module import.

However, have you tried the full module mocking?

import moduleMock from '@third/prod-data-component'

jest.mock('@third/prod-data-component')

describe('test scenario', () => {
  it('should show correct product data', () => {
    moduleMock.useProductData.mockReturnValue(...)
  })
})

EDIT

I missed the Typescript part. You need to wrap the actual module type definitions with Jest's own type definitions.

I solved this problem in the past in the following way, using jest.mocked function:

import prod_data_component_module from '@third/prod-data-component'

jest.mock('@third/prod-data-component')

describe('Your test case scenario', () => {
  const mock = jest.mocked(prod_data_component_module, { shallow: true })

  it('Your test here', async () => {
    mock.useProductData.mockReturnValue('...')

    // test logic here
  })
})

mock is a jest wrapper of the original module. It is of type jest.MockedFn<T>, so it contains actual exported types/functions and also jest mocks.

  • Related