javascript - 如何在 Sinon.js 中测试 Controller 中使用的辅助函数

标签 javascript node.js mocha.js sinon sinon-chai

我正在使用 sinon.js 来测试我的 API。 我想测试被调用的辅助函数的顺序。

controller.js

exports.controllerFunction = async (req, res) => { 

    const function1Results = await function1(paramm);

    const function2Results = await function2(param, function1Results);

    return res.send(function2Results);
};

helpers.js

exports.function1 = function(param) {
 return param;
}

exports.function2 = function(param, func) {
 return param;
}

unitTest.js

const controller = require('./controller.js')
const helpers = require('./helpers.js')

describe('Unit test cycle', () => {
 beforeEach(() => {
  // Spies
  sinon.spy(controller, 'controllerFunction');
  sinon.spy(helpers, 'function1');
  sinon.spy(helpers, 'function2');

  // Function calls
  controller.controllerFunction(this.req, this.res)
 })

 afterEach(() => {
  sinon.restore();
 })

 this.req = {}
 this.res = {}

 it('should call getAvailability', (done) => {
  expect(controller.controllerFunction.calledOnce).to.be.true
  expect(helpers.function1.calledOnce).to.be.true
  expect(helpers.function2.calledOnce).to.be.true
 });
})

expect(controller.controllerFunction.calledOnce).to.be.true

返回为 true

  expect(helpers.function1.calledOnce).to.be.true
  expect(helpers.function2.calledOnce).to.be.true

并且以 false 的形式出现。

因为我的辅助函数正在 Controller 中使用,所以它们也应该被调用,但它们没有。

那么在测试 Controller 时,我该如何测试我的辅助函数是否也被调用了呢?

最佳答案

我会尝试试一试。因为你的函数是 async 我认为你的测试 block 应该为 await 做。

我建议将函数调用移到 it 命令 block 中。 beforeEach 通常用于设置,afterEach 用于清除一些数据/模拟(也称为撕裂)。

尝试

it('should call getAvailability', async (done) => {
  // When
  await controller.controllerFunction(this.req, this.res)
  // Assert
  expect(controller.controllerFunction.calledOnce).to.be.true
  expect(helpers.function1.calledOnce).to.be.true
  expect(helpers.function2.calledOnce).to.be.true
  done && done()
 });

不要忘记从 beforeEach 中删除函数调用。

关于javascript - 如何在 Sinon.js 中测试 Controller 中使用的辅助函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59430499/

相关文章:

javascript - 如果无法连接到服务器,则 Socket.io 客户端触发事件

javascript - 如何为 HTML 元素编写 Mocha 测试用例?

javascript - 按下某个键时忽略延迟?

javascript - python 解密 jscrypt 中加密的文本

javascript - 显示单选按钮在 PHP/HTML 中无法正常工作

node.js - 使用字体超棒的图标而不是项目符号动态创建列表

javascript - Firebase http 函数在 http 请求库返回数据之前完成

javascript - 如何使用 .mocharc 配置文件指定测试文件

javascript - expect in chai 如何处理文本字符串?

javascript - 更改当前关闭状态?