我刚刚开始考虑在我的 hapi Web 应用程序中添加一些自动化单元测试,我正在使用 lab 和 sinon 来做到这一点。 由于某种原因,我无法对 sinon 进行第一次测试来存根在 get 处理程序中进行的函数调用。 这是获取处理程序:
const { mytest } = require('../services/my-service')
module.exports = [
{
method: 'GET',
path: `${urlPrefix}/healthcheck-detailed`,
config: {
auth: false
},
handler: async (request, h) => {
mytest()
return h.response('Success').code(200);
}
}]
被调用的函数的 my-service 看起来像这样
function mytest(){
console.log("My test called")
}
module.exports = { mytest }
测试看起来像这样
const Lab = require('@hapi/lab');
const Code = require('@hapi/code');
const { expect } = Code;
const { it, describe, before, after, beforeEach, afterEach } = exports.lab = Lab.script();
const { init } = require('../../../server/')
const sinon = require('sinon')
describe('Healthcheck /get', () => {
let server
let mytestStub
beforeEach(async () => {
server = await init()
// Stub the mytest function directly using the full module path
mytestStub = sinon.stub(require('../../../server/services/my-service'), 'mytest').callsFake(() => {
console.log("Stubbed mytest called");
});
})
afterEach(async () => {
await server.stop()
// Restore the original mytest function
mytestStub.restore();
})
it('calls the correct functions on /healthcheck-detailed', { timeout: 30000 }, async () => {
const response = await server.inject({
method: 'GET',
url: '/healthcheck-detailed'
})
console.log("Stub called: ", mytestStub.called);
expect(mytestStub.calledOnce).to.be.true();
})
});
当我运行此命令时,我希望测试能够通过,并且控制台输出应显示“Stubbed mytest Called”,但它失败并显示“My Test Called”。我缺少什么?为什么存根会被忽略?
@fosbie 在导入时不要破坏被测试的存根方法。 应该显式导入它。
const myService = require('../services/my-service')
module.exports = [
{
method: 'GET',
path: `${urlPrefix}/healthcheck-detailed`,
config: {
auth: false
},
handler: async (request, h) => {
myService.mytest()
return h.response('Success').code(200);
}
}]
请参阅说明这里