【问题标题】:How to mock const peer it in jest如何开玩笑地模拟 const 对等
【发布时间】:2020-09-10 14:06:54
【问题描述】:

关于如何在它的测试中模拟 const 有数百万个问题,但没有一个有效。

有人可以提供如何为it 模拟import isNode from 'detect-node'; 的工作解决方案吗? (https://www.npmjs.com/package/detect-node)

我的代码没有t work. Its not mocking isNode` 始终为真。

例子:

测试文件:

import { myTestFn } from './fn'
 
describe(('TEST'), () => {
    it(('node mock false'), () => {
        jest.doMock('detect-node', () => false);
        myTestFn(); // will print constant
    });

    it(('node mock true'), async () => {
        jest.doMock('detect-node', () => true);
        myTestFn(); // will print constant
    });
});

Fn 文件:

import isNode from 'detect-node';
export const myTestFn = () => console.log({isNode})

例外的输出是:

false (for 'node mock false')
true (for 'node mock true')

我尝试了很多方法,使用 doMock、mock、mock in test、mock outside test……

我正在使用“开玩笑”:“^26.4.2”,

非常感谢您的帮助!

【问题讨论】:

    标签: javascript node.js unit-testing mocking jestjs


    【解决方案1】:

    你应该在模拟之后使用jest.resetModules() 和动态import('./fn')

    重置模块注册表 - 所有必需模块的缓存。这对于隔离测试之间本地状态可能发生冲突的模块很有用。

    例如

    fn.ts:

    import isNode from 'detect-node';
    
    export const myTestFn = () => console.log({ isNode });
    

    fn.test.ts:

    describe('63811749', () => {
      beforeEach(() => {
        jest.resetModules();
      });
      it('node mock false', async () => {
        jest.doMock('detect-node', () => false);
        const { myTestFn } = await import('./fn');
        myTestFn();
      });
    
      it('node mock true', async () => {
        jest.doMock('detect-node', () => true);
        const { myTestFn } = await import('./fn');
        myTestFn();
      });
    });
    

    单元测试结果:

     PASS  src/stackoverflow/63811749/fn.test.ts
      63811749
        ✓ node mock false (13ms)
        ✓ node mock true (2ms)
    
      console.log src/stackoverflow/63811749/fn.ts:3
        { isNode: false }
    
      console.log src/stackoverflow/63811749/fn.ts:3
        { isNode: true }
    
    Test Suites: 1 passed, 1 total
    Tests:       2 passed, 2 total
    Snapshots:   0 total
    Time:        4.749s, estimated 12s
    

    【讨论】:

    • 如果不直接在测试中导入我的组件,我有什么办法吗?
    • @nirebam368 这是一个不同的问题吗?如果是这样,请提出一个新问题。
    • 不,它与我的问题有关,我在文件顶部导入。看起来我在测试中导入反应组件时出现了一些问题const Home = await import('./home'); 我得到了Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.
    猜你喜欢
    • 2019-07-09
    • 2020-08-20
    • 2020-11-18
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    • 2021-05-27
    • 2022-01-24
    • 1970-01-01
    相关资源
    最近更新 更多