【问题标题】:Mock a react hook with different return values模拟具有不同返回值的反应钩子
【发布时间】:2023-02-07 00:59:08
【问题描述】:

我想根据自定义挂钩的返回值测试一个反应组件,该组件是否显示元素列表。

在我的第一个测试中,我想确保不显示任何内容,所以我在测试方法的顶部使用了它:

jest.mock('components/section/hooks/use-sections-overview', () => {
  return {
    useSectionsOverview: () => ({
      sections: [],
    }),
  };
});

在第二次测试中,我想展示一些东西,所以我用了这个

jest.mock('components/section/hooks/use-sections-overview', () => {
  return {
    useSectionsOverview: () => ({
      sections: [
         {id: '1', content: 'test'}
      ],
    }),
  };
});

不幸的是,在运行我的测试时,它总是返回一个空数组。

我尝试在我的 afterEach 方法中添加 jest.restoreAllmocks();,但这并没有改变任何东西。

我错过了什么吗?

【问题讨论】:

    标签: reactjs jestjs


    【解决方案1】:

    jest.mock 将始终被拉到文件的顶部并首先执行,因此您的测试不能更改超出初始模拟的模拟。

    不过,您可以做的是在某种存根响应处设置模拟点,将其包装在 jest.fn 调用中(以延迟执行),以便在每次更改后对其进行评估。

    例如

    const sections_stub = {
        sections: [],
    };
    
    jest.mock('components/section/hooks/use-sections-overview', () => ({
        useSectionsOverview: jest.fn(() => sections_stub),
    }));
    
    describe('my component', () => {
        it('test 1', () => {
             sections_stub.sections = [];
    
              // run your test
        });
        it('test 2', () => {
             sections_stub.sections = [
                { id: '1', content: 'test'}
             ];
    
              // run your other test
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2020-06-01
      • 2020-06-19
      • 1970-01-01
      • 1970-01-01
      • 2022-09-11
      • 1970-01-01
      • 2021-11-11
      • 2020-07-07
      • 1970-01-01
      相关资源
      最近更新 更多