用一个玩笑将一个模块的多个模型放在一个文件中

时间:2019-07-15 15:02:27

标签: javascript jestjs

我必须执行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'

testFile

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时,它可以工作,但我只能在文件上实现一个模拟。做模拟不起作用。如果有人可以提供一些示例说明如何解决这个问题,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

您可以使用间谍代替模拟。由于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);
    });
});

类似的东西。