garbles
garbles

Reputation: 73

Verify hapi server.log is being called with expected message

I have a requirement to verify that certain actions are being logged to the server and would like to know why I'm having trouble stubbing the call to hapi server.log().

In my unit tests I instantiate a hapi server using:

const Hapi = require('hapi');
const server = new Hapi.Server();

I have my stub setup as:

const Sinon = require('sinon');
const logStub = Sinon.stub(server, 'log');

I am using server.inject to call the endpoint that I expect to call server.log. When I debug the test, I have a breakpoint set to verify that server.log is being called in my endpoint and I have a breakpoint in my unit test to verify that the logStub is being called. However, when I call this:

server.inject(localRequest).then(() => {
  const spyCall = logStub.getCall(0);
})

spyCall is null and if I inspect logStub, called is false and the callCount is 0, despite server.log being called in my endpoint.

What am I missing here? Does calling server.inject cause an issue with stubbing methods on the hapi server?

Upvotes: 3

Views: 140

Answers (1)

garbles
garbles

Reputation: 73

The best solution I have been able to find is to use the server.once method on the hapi server.

I neglected to mention in my question that I'm using hapi version 16.6.2 so this solution may not work for the latest version of hapi as it is much different.

server.once({
  name: 'log',
  filter: 'myTag',
  }, (update) => {
    Code.expect(update.data).to.equal('expectedMessage');
    });

Using this approach allowed me to specify the event 'log' and the specific tag (or tags) for my log event. Hope this helps someone else!

Upvotes: 2

Related Questions