1

I trying to mock function from route handler...

Here is my route:

server.route({
  method: 'GET',
  path: '/api/color/{format}',
  handler: this.pingLogic.getPing,
  config: {
    description: 'This is ping route',
    tags: ['api', 'v1', 'ping route'],
    validate: {
      params: pingValidator
    }
  }
})

getPing function looks like this:

getPing(req: HapiRequest, reply: Hapi.ReplyNoContinue): any {
  req.seneca
    .act(
      {
        role: 'color',
        format: req.params.format,
        color: 'red'
      },
      (err: any, out: any): any => {
        return reply(err || out)
      }
    )
}

Here is my test:

L.test('returns the hello message as text.', (done) => {
  const ping = new PingLogic;
  sinon.stub(ping, 'getPing').returns({});
  server.inject('/api/color/hex', (response: any) => {
    expect(response.payload).to.equal({color: 'green'});
    done();
  });
});

It not working it not recognise this part: sinon.stub(ping, 'getPing').returns({}); Anyone know how to make this work?

P.S.
  • 15,970
  • 14
  • 62
  • 86
Vladimir
  • 1,751
  • 6
  • 30
  • 52

1 Answers1

0

I just solved this same problem using proxyquire over sinon.

const route = proxyquire('./route', {
  './pingLogic': {
    default: sinon.stub().callsArgWith(1, 'response'),
  },
}).default;

server.route(route);

server.inject({ request }) // Calls my stub

Another solution might be something like this:

In your route file:

handler: (request, reply) => { this.pingLogic.getPing(request, reply); }

Then you can stub pingLogic as usual.

I think this is because hapi registers the real object when you require it, and stubbing it after that is too late. If you wrap it in an arrow function, sinon can override the logic before the function is bound to the hapi route object.

Findlay
  • 134
  • 1
  • 8