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?

1 Answer 1

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");
});
Sign up to request clarification or add additional context in comments.

1 Comment

Some eslint configurations may throw errors when <any> is used. I over came this with const main = () => jest.fn((message) => message)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.