我有一个导出两个函数的文件,a
其中调用.b
b
a
我想模拟a
测试,当我调用 时b
,它会a
使用一些参数进行调用,但由于这两个函数位于同一个文件中,所以我找不到任何方法来执行此操作。
functions.js
export const a = (x) => { a very complicated function };
export const b = (x) => a(x+1);
Run Code Online (Sandbox Code Playgroud)
functions.test.js
import { a, b } from './functions';
describe('b', () => {
test('calling b calls a with x+1', () => {
const fakeA = //mock function a ... don't know how to.
b(1);
expect(fakeA).toHaveBeenCalledWith(2);
});
});
Run Code Online (Sandbox Code Playgroud)
经过大量研究,我发现有两种方法可以实现这一目标:
exports.a
而不是a
在b
函数中:functions.js
export const a = (x) => { a very complicated function };
export const b = (x) => exports.a(x+1);
Run Code Online (Sandbox Code Playgroud)
functions.test.js
import * as functions from './functions';
describe('b', () => {
test('calling b calls a with x+1', () => {
functions.a = jest.fn();
functions.b(1);
expect(functions.a).toHaveBeenCalledWith(2);
});
});
});
Run Code Online (Sandbox Code Playgroud)
b
为接受函数,默认为a
:functions.js
export const a = (x) => { a very complicated function };
export const b = (x, a = exports.a) => a(x + 1);
Run Code Online (Sandbox Code Playgroud)
functions.test.js
import { a, b } from './functions';
describe('b', () => {
test('calling b calls a with x+1', () => {
const fakeA = jest.fn();
b(1, fakeA);
expect(fakeA).toHaveBeenCalledWith(2);
});
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5307 次 |
最近记录: |