2

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

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!"
      }
    };
  }
}

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?

Bas
  • 21
  • 2

1 Answers1

5

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");
});
PerfectlyPanda
  • 3,271
  • 1
  • 6
  • 17
  • Some eslint configurations may throw errors when `` is used. I over came this with `const main = () => jest.fn((message) => message)` – moys Dec 19 '22 at 07:14