gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 01:47:48 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com