我正在努力使用 spyOn 作为测试我的 utils.js 模块的一部分。我尝试了各种方法和方法,但似乎都产生了“预期的模拟函数已被调用”。作为记录,其他单元测试工作正常,所以我的实际测试设置应该没有任何问题。
下面是一个包含两个函数和一个测试的简化测试用例,但我什至无法让它们工作。我是否完全误解了 spyOn?
// utils.js
function capitalHelper(string){
return string.toUpperCase();
}
function getCapitalName(inputString){
return capitalHelper(inputString.charAt(0)) + inputString.slice(1);
}
exports.capitalHelper = capitalHelper
exports.getCapitalName = getCapitalName
// utils.test.js
const Utils = require('./utils');
test('helper function was called', () => {
const capitalHelperSpy = jest.spyOn(Utils, 'capitalHelper');
const newString = Utils.getCapitalName('john');
expect(Utils.capitalHelper).toHaveBeenCalled();
})
最佳答案
我不会使用 spyOn(),但会为所有模拟场景使用 jest.fn()
在你的情况下我会做以下事情
test('helper function was called', () => {
Utils.capitalHelper = jest.fn((s) => Utils.capitalHelper(s))
const newString = Utils.getCapitalName('john')
expect(Utils.capitalHelper.mock.calls.length).toBe(1)
})
第一行可以简单地是:
Utils.capitalHelper = jest.fn()
因为您似乎没有在测试中测试返回值:)
您可以在 jest 官方文档中找到有关 jest.fn() 的更多详细信息:https://facebook.github.io/jest/docs/en/mock-functions.html
--------------------编辑
我明白了:出现问题是因为在您的 utils.js 文件中,getCapitalName 使用了定义的函数,而不是导出所指向的函数。
为了能够模拟正在使用的函数,您可以将 utils.js 文件更改为
// utils.js
const Utils = {
capitalHelper: string => string.toUpperCase(),
getCapitalName: inputString => Utils.capitalHelper(inputString.charAt(0)) + inputString.slice(1)
}
export default Utils
那么我之前给出的测试就可以了
关于javascript - Jest onSpy - 预期模拟函数已被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50719494/