【发布时间】:2019-06-21 16:17:05
【问题描述】:
我有一个只有一个导出函数和几个非导出函数的模块来保持 api“干净”。我正在尝试使用 jest & require 编写单元测试,但出现以下错误:
Error: expect(jest.fn())[.not].toBeCalledTimes()
jest.fn() value must be a mock function or spy.
Received:
function: [Function doMagic]
如果我尝试进行间谍活动,我如何才能获得通过rewire (或其他验证方法被调用频率的其他方式)可见的非导出方法的监视,尽管能够在最后一次测试中调用函数如下所示:Cannot spy the doMagic property because it is not a function; undefined given instead
我的场景的简单示例:
例如functions.js
const moreFunctions = require("./moreFunctions");
const theExportedFunction = someNumber => {
return doMagic(someNumber);
};
function doMagic(someNumber) {
if (someNumber % 2 === 0) {
return moreFunctions.getTrue();
}
return moreFunctions.getFalse();
}
module.exports = { theExportedFunction };
其他模块: moreFunctions.js
const moreFunctions = {
getTrue: () => true,
getFalse: () => false
};
module.exports = moreFunctions;
我是如何测试它的: functions.test.js
const rewire = require("rewire");
const functions = rewire("./functions");
const moreFunctions = functions.__get__('moreFunctions');
const doMagic = functions.__get__('doMagic');
const getFalse = jest.spyOn(moreFunctions, 'getFalse');
const getTrue = jest.spyOn(moreFunctions, 'getTrue');
describe("testing inner functions ", () => {
afterEach(() => {
jest.clearAllMocks();
});
test('theExportedFunction calls doMagic with 1 returns false and does not call getTrue', () => {
const result = functions.theExportedFunction(1);
console.log('result: ' + result);
expect(result).toBe(false);
//expect(doMagic).toBeCalledTimes(1); // this blows up
expect(getTrue).toHaveBeenCalledTimes(0);
expect(getFalse).toHaveBeenCalledTimes(1);
});
test('theExportedFunction calls doMagic with 2 returns true and does not call getFalse', () => {
const result = functions.theExportedFunction(2);
console.log('result: ' + result);
expect(result).toBe(true);
//expect(doMagic).toBeCalledTimes(1); // this blows up
expect(getTrue).toHaveBeenCalledTimes(1);
expect(getFalse).toHaveBeenCalledTimes(0);
});
// This works!
test('just testing to see if i can call the doMagic function', () => {
const result = doMagic(2);
expect(result).toBe(true);
expect(getTrue).toHaveBeenCalledTimes(1);
expect(getFalse).toHaveBeenCalledTimes(0);
});
});
【问题讨论】:
标签: javascript unit-testing module jestjs private