我一直在测试我的Azure函数,但是我无法模拟上下文日志函数。
例如,我具有以下Azure功能:
module.exports = async function (context, req) {
if (req.query.isGood) {
context.log("Goooood!!!")
context.res = {
body: {
message: "This is good!"
}
};
} else {
context.log.error("Not gooood!!!")
context.res = {
status: 404,
body: {
message: "This is not good!"
}
};
}
}
因此,我想检查某个日志发生的次数,例如,'log.error'发生一次,'log'发生两次,但是我无法模仿。
我尝试了几种类似的组合:
log: {
"": jest.fn(),
"error": jest.fn()
}
至此,我对如何模拟这些功能一无所知,并且想知道是否有可能?以及如何创建此类功能?
为了做到这一点,您需要立即调用create a closure function。在该函数内部,创建默认值,然后向其添加其他方法。在Typescript中,您需要将jest.fn()
强制转换为任何类型,以避开类型检查。
log: (function() {
let main = <any>jest.fn((message) => message) ;
let info = jest.fn((message) => message);
main.info = info;
return main;
})()
一旦您回到测试中,它便应表现出预期的效果:
test ('log test', () => {
context.log("foo");
context.log.info("bar");
expect(context.log.mock.calls[0][0]).toEqual("foo");
expect(context.log.info.mock.calls[0][0]).toEqual("bar");
});