【问题标题】:Several mocks of one module in one file with jest一个文件中一个模块的几个模拟,开玩笑
【发布时间】:2019-11-24 07:36:50
【问题描述】:

我必须使用例如 a、b 的函数。它们都是一个模块的元素,它们在 index.js 中重新导出。 Function a 调用 function b

如果我在文件顶部使用jest.mock,这一切都有效,但如果我想在每个it 块中指定b 函数的不同模拟实现,则它不起作用。我也尝试使用jest.doMock,但效果不佳。

a.js

import * as fromDependencies from '.'
export function(arg) {
    return !fromDependencies && !arg;
}

b.js

export function b() {
    //some code 
    return boolean;
}

index.js

export * from 'a.js',
export * from 'b.js'

测试文件

import a from '../a.js';

describe('isGroupOverlaidTest', () => {
    it('should return false', () => {
       jest.mock('../.', () => ({
           b: jest.fn(() => true);
       }))

        expect(a(true)).toBe(false);
    });

    it('should return true', function() {
        jest.mock('../.', () => ({
           b: jest.fn(() => false);
       }))

       expect(a(false)).toBe(false);
    });
});

结果是假的,无论如何我想调用我的模拟函数而不是原始函数。当我在文件顶部有 jest.mock 时,它可以工作,但我只能为文件实现一个模拟。做模拟是行不通的。如果有人能提供一些我如何解决这个问题的例子,我将不胜感激;)。

【问题讨论】:

标签: javascript jestjs


【解决方案1】:

您可以使用间谍而不是模拟。由于a 导出的是函数而不是对象,因此您必须将其包装起来。

import a from '../a.js'

const aWrapped = { a }

describe('isGroupOverlaidTest', () => {
    it('should return false', () => {
       const mockA = jest.fn()
       const spyedA jest.spyOn(aWrapped, a).mockReturnValue(mockA)

        expect(spyedA(true)).toBe(false);
    });
});

类似的东西。

【讨论】:

  • 对不起,这是我的错误,它应该是从另一个模块模拟的 b 函数。现在我编辑了帖子。但无论如何,如果我为 b 尝试了这个解决方案,它不起作用并且仍然调用原来的函数:(
猜你喜欢
  • 2020-01-31
  • 2018-10-23
  • 2018-03-02
  • 1970-01-01
  • 1970-01-01
  • 2020-03-05
  • 1970-01-01
  • 2020-05-17
  • 2019-11-04
相关资源
最近更新 更多