【问题标题】:Mock custom hook from 3rd party library in Jest从 Jest 中的第 3 方库模拟自定义挂钩
【发布时间】:2022-11-30 22:52:39
【问题描述】:

我在我的 React 项目中使用来自第三方库的自定义挂钩:

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

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

在我的玩笑测试中,我想模拟钩子的返回值,我试过:

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

当我运行测试时,上面的模拟没有任何效果。

如何模拟来自第 3 方库的自定义挂钩的返回值?

【问题讨论】:

  • 你试过了吗jest.requireActual("@third/prod-data-component");

标签: reactjs typescript unit-testing react-hooks


【解决方案1】:

阅读您的示例,您可能缺少实际的模块导入。

但是,您是否尝试过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(...)
  })
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-11
    • 2020-08-15
    • 1970-01-01
    • 2021-04-17
    • 2019-09-08
    • 2023-01-26
    • 1970-01-01
    • 2022-06-17
    相关资源
    最近更新 更多