简体   繁体   English

从 Jest 中的第 3 方库模拟自定义挂钩

[英]Mock custom hook from 3rd party library in Jest

I am using a custom hook from 3rd party library in my React project:我在我的 React 项目中使用来自第三方库的自定义挂钩:

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:该钩子 function 的签名是:

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?如何模拟来自第 3 方库的自定义挂钩的返回值?

==== 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.但也不起作用。

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

Reading your example, you may be missing the actual module import.阅读您的示例,您可能缺少实际的模块导入。

However, have you tried the full module mocking ?但是,您是否尝试过完整模块 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.我错过了 Typescript 部分。 You need to wrap the actual module type definitions with Jest's own type definitions.您需要用 Jest 自己的类型定义来包装实际的模块类型定义。

I solved this problem in the past in the following way, using jest.mocked function:我过去通过以下方式解决了这个问题,使用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. mock是原始模块的开玩笑包装器。 It is of type jest.MockedFn<T> , so it contains actual exported types/functions and also jest mocks.它是jest.MockedFn<T>类型,因此它包含实际导出的类型/函数以及玩笑模拟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM