如何使用jest在同一模块中模拟函数 [英] How to mock functions in the same module using jest

查看:67
本文介绍了如何使用jest在同一模块中模拟函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正确模拟以下示例的最佳方法是什么?

What's the best way to correctly mock the following example?

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

The problem is that after import time, foo keeps the reference to the original unmocked bar.


module.js:

module.js:



export function bar () {
    return 'bar';
}

export function foo () {
    return `I am foo. bar is ${bar()}`;
}




module.test.js:

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)); // outputs true

        module.bar.mockReturnValue('fake bar');

        console.log(module.bar()); // outputs 'fake bar';

        expect(module.foo()).toEqual('I am foo. bar is fake bar');
        /**
         * does not work! we get the following:
         *
         *  Expected value to equal:
         *    "I am foo. bar is fake bar"
         *  Received:
         *    "I am foo. bar is bar"
         */
    });
});

谢谢!

编辑:我可以更改:

export function foo () {
    return `I am foo. bar is ${bar()}`;
}

export function foo () {
    return `I am foo. bar is ${exports.bar()}`;
}

但这是p。在我看来,到处都是丑陋的:/

but this is p. ugly in my opinion to do everywhere :/

推荐答案

fwiw,我解决的解决方案是使用依赖注入,通过设置默认参数。

fwiw, the solution I settled on was to use dependency injection, by setting a default argument.

所以我会更改

export function bar () {
    return 'bar';
}

export function foo () {
    return `I am foo. bar is ${bar()}`;
}

export function bar () {
    return 'bar';
}

export function foo (_bar = bar) {
    return `I am foo. bar is ${_bar()}`;
}

这不是我组件API的重大变化,我可以通过执行以下操作轻松覆盖我的测试中的栏

This is not a breaking change to the API of my component, and I can easily override bar in my test by doing the following

import { foo, bar } from '../src/module';

describe('module', () => {
    it('foo', () => {
        const dummyBar = jest.fn().mockReturnValue('fake bar');
        expect(foo(dummyBar)).toEqual('I am foo. bar is fake bar');
    });
});

这样做的好处是可以带来更好的测试代码:)

This has the benefit of leading to slightly nicer test code too :)

这篇关于如何使用jest在同一模块中模拟函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆