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

标签 javascript unit-testing mocking jestjs spy

我正在努力使用 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/

相关文章:

c# - 如何测试在被测类中调用的方法?

javascript - 如何使用 Javascript/jQuery 隐藏/显示启用/禁用 HTML 元素?

javascript - localStorage,我似乎无法调用数据

javascript - 为什么我的轮播图像旁边有额外的空间?

http - Karma 测试中出现错误 : No provider for HttpService!

python - 如何在 python 单元测试中模拟连接错误和请求超时

.net - 为什么 Moq 不运行重写的 ToString 方法?

javascript - 分配以数字结尾的 CSS 字体系列

unit-testing - 在 junit 3 中为测试套件指定测试方法名称前缀

c++ - c 的单元测试 - 如何在不重新编译/重新链接的情况下测试 'unit'?