相关疑难解决方法(0)

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

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

问题是在导入时间之后,foo保持对原始未引用的引用bar.

module.js:

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

export function foo () {
    return `I am foo. bar is ${bar()}`;
}
Run Code Online (Sandbox Code Playgroud)

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');
        /**
         * …
Run Code Online (Sandbox Code Playgroud)

javascript testing mocking jestjs

48
推荐指数
6
解决办法
1万
查看次数

开玩笑的模拟内部功能

我有一个名为helper.js的文件,其中包含两个函数

export const funcA = (key) => {
   return funcB(key)
};

export const funcB = (key,prop) => {
   return someObj;
};
Run Code Online (Sandbox Code Playgroud)

我有我的helper.spec.js来测试helper.js文件的功能。

import {funcA,funcB} from 'helper';

describe('helper', () => {
   test('testFuncB', () => {

   }
   test('testFuncA', () => {

   }
}
Run Code Online (Sandbox Code Playgroud)

对funcB的测试非常简单,我只调用它并期望someObj
。问题是测试funcA,为了对其进行测试,我想模拟funcB的响应。

我希望testFuncB调用实际的funcB,testFuncA调用模拟的funcB

我如何在两个测试中实现对funcB的模拟和原创?

这不是重复项。这是不同的情况:它们仅模拟内部调用的函数,如果我删除了testFuncB,那将是相同的,但是我也必须对testFuncB进行测试。

javascript jestjs

12
推荐指数
2
解决办法
1万
查看次数

标签 统计

javascript ×2

jestjs ×2

mocking ×1

testing ×1