如何使用Jest在同一模块中模拟函数?

13 浏览
0 Comments

如何使用Jest在同一模块中模拟函数?

如何正确模拟以下示例的最佳方法?

问题在于在导入时间之后,foo 保留对未模拟的原始 bar 的引用。

module.js

export function bar () {
    return 'bar';
}
export function foo () {
    return `我是foo。bar 是 ${bar()}`;
}

module.test.js

import * as module from '../src/module';
describe('module', () => {
    let barSpy;
    beforeEach(() => {
        barSpy = jest.spyOn(
            module,
            'bar'
        ).mockImplementation(jest.fn());
    });
    afterEach(() => {
        barSpy.mockRestore();
    });
    it('foo', () => {
        console.log(jest.isMockFunction(module.bar)); // 输出 true
        module.bar.mockReturnValue('fake bar');
        console.log(module.bar()); // 输出 'fake bar';
        expect(module.foo()).toEqual('我是foo。bar 是 fake bar');
        /**
         * 不起作用!我们得到以下结果:
         *
         *  期望值等于:
         *    "我是foo。bar 是 fake bar"
         *  收到的值:
         *    "我是foo。bar 是 bar"
         */
    });
});

我可以更改:

export function foo () {
    return `我是foo。bar 是 ${bar()}`;
}

为:

export function foo () {
    return `我是foo。bar 是 ${exports.bar()}`;
}

但我认为这样做到处都很丑陋。

0