【问题标题】:How to test a helper functions used in controller in Sinon.js如何在 Sinon.js 中测试控制器中使用的辅助函数
【发布时间】:2020-04-13 06:39:13
【问题描述】:

我正在使用 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 的形式出现。

因为控制器中使用了我的辅助函数,所以它们也应该被调用,但它们不是。

那么我如何测试我的辅助函数在测试控制器时是否也被调用了?

【问题讨论】:

  • 您是否尝试在这些功能上设置间谍?
  • 是的,我会编辑问题。谢谢!

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


【解决方案1】:

我会尝试试一试。由于您的功能是async,我认为您的测试块应该是await

我建议将函数调用移动到 it 命令块中。 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 中删除函数调用。

【讨论】:

  • 不错的尝试。这是我得到的错误:理解它现在抛出异常错误:解决方法被过度指定。指定回调 * 或 * 返回一个 Promise;不是两者。
  • 感谢您的尝试,但没有成功。
猜你喜欢
  • 2011-09-20
  • 1970-01-01
  • 2015-11-09
  • 2014-12-28
  • 1970-01-01
  • 1970-01-01
  • 2011-08-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多