我一直在测试我的 Azure Functions,但无法模拟上下文日志函数。
例如,我有以下 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()
转换为 any 类型以绕过类型检查。
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");
});
关于javascript - 在 javascript 中使用 jest 模拟 Azure Function 上下文上的不同日志级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61732004/