用JavaScript嘲笑Azure Function上下文中的不同日志级别 [英] Mocking different log levels on Azure Function context with jest in javascript

查看:49
本文介绍了用JavaScript嘲笑Azure Function上下文中的不同日志级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在测试我的Azure函数,但是无法模拟上下文日志函数.

I have been playing around with testing my Azure Functions, but I am unable to mock the context log function.

例如,我具有以下Azure功能:

For example I have the following Azure Function:

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"发生两次,但是我无法模拟.

So I want to check the amount of times a certain log occured, for example 'log.error' occured once and 'log' occured twice, but I am unable to mock this.

我尝试了几种组合,例如:

I tried a couple of combinations like:

log: {
      "": jest.fn(),
      "error": jest.fn()
}

在这一点上,我对如何模拟这些功能一无所知,并且想知道是否有可能?以及如何创建这类功能?

At this point I'm clueless on how to mock these functions, and am wondering if it is even possible? And how do you create these kind of functions?

推荐答案

为此,您需要

In order to do this you need to create a closure function that is immediately invoked. Inside that function, create your default and then add to it the additional methods. In Typescript, you need to cast jest.fn() to the any type to get around type checking.

log: (function() { 
    let main = <any>jest.fn((message) => message) ;

    let info = jest.fn((message) => message); 
    main.info = info;

    return main;
})()

一旦您回到测试中,它便应表现出预期的效果:

Once you are back in your test, this should then behave as expected:

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嘲笑Azure Function上下文中的不同日志级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆