【问题标题】:How do i mock and customise the values of a function imported from a npm package using Jest?如何使用 Jest 模拟和自定义从 npm 包导入的函数的值?
【发布时间】:2019-10-30 18:13:26
【问题描述】:

我在我的 React 组件say(SampleComponent.js) 中使用“react-device-detect”npm 包中的isMobileOnly

我想在我的笑话单元测试中自定义isMobileOnly 的返回值。

我已经尝试过 Jest 手动模拟,如下面的链接中所述: https://jestjs.io/docs/en/manual-mocks

但这似乎对我不起作用。

我也试过: 开玩笑的模拟实现 jest's mockImplementationOnce 开玩笑的间谍

import {isMobileOnly} from 'react-device-detect;

在我开玩笑的单元测试中,我想模拟函数isMobileOnly,这样我应该能够将其返回值自定义为“true”。默认值为“false”。

【问题讨论】:

    标签: reactjs unit-testing mocking jestjs


    【解决方案1】:

    这对我有用。

    在您的测试文件中,添加以下内容:import * as deviceDetect from 'react-device-detect';

    然后您可以更改以下内容:deviceDetect.isMobileOnly = true;

    例如。

    import * as deviceDetect from 'react-device-detect'; //<--important
    
    it.only('clicking on myAccount redirects to /user/myAccount', () => {
    
            ///make sure this is before mount or shallow
            deviceDetect.isMobileOnly = true; //<--important
    
            component = mount(<Provider store={store}><Sidebar history={mockedHistory} /></Provider>);
            component.find('[test-id="myAccount"]').first().simulate('click');
            expect(mockedHistory.push).toHaveBeenCalledWith('/user/myAccount');
        });
    

    【讨论】:

    • 这需要启用自动模拟吗?
    【解决方案2】:

    终于!经过数小时的努力,我自己弄清楚了。这是我所做的:

    1. 在 node_modules 目录的同一级别中创建了__mocks__ 文件夹,其中包“react-device-detect”可用。注意:对于__mocks__,小写很重要。
    2. __mocks__ 文件夹中创建了一个名为“react-device-detect.js”的文件。
    3. 在其中添加了以下代码:

      const deviceDetect = jest.genMockFromModule('react-device-detect');
      deviceDetect.isMobileOnly = true;
      module.exports = deviceDetect;
      
    4. 在测试文件中,我像在原始文件中一样导入了“isMobileOnly” 组件:

      import { isMobileOnly } from 'react-device-detect';
      
    5. 现在,我可以在 根据单元测试用例的需要模拟文件。

    更多详情请参考官方文档https://jestjs.io/docs/en/manual-mocks

    感谢@Roman 与我们联系!

    【讨论】:

    • 当您尝试在测试文件中使用deviceDetect 时,是否没有找到模块?你在做什么看起来不错,但它不适合我。
    【解决方案3】:

    您可以覆盖用户代理以进行测试,因此react-device-detect 包会按照您的需要识别它,here 的方法是。

    This 主题也应该有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-04
      • 2020-04-24
      • 2020-02-26
      • 2021-08-08
      • 2019-02-25
      相关资源
      最近更新 更多