Jest onSpy - 预期模拟函数被调用

时间:2018-06-06 11:38:29

标签: javascript unit-testing mocking jestjs spy

我正在努力使用spyOn作为测试我的utils.js模块的一部分。我尝试了各种方法和方法,但似乎所有人都希望将#34;预期的模拟函数调用为#34;。为了记录,其他单元测试工作正常,因此我的实际测试设置不应该出现任何问题。

下面是一个简化的测试用例,包含两个函数和一个测试,我甚至无法使用它们。我是否完全误解了间谍?



// 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();
})




1 个答案:

答案 0 :(得分:1)

我使用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

然后我之前的测试将起作用