Search code examples
node.jstypescripthapi

Set params on request when testing hapi routes


I am currently writing some tests for our hapi routes. The route I want to test looks like that:

server.route(
  {
    method: 'POST',
    path: '/',
    options: {
      tags: ['api'],
      cors: true,
      handler: async (req: Hapi.Request | any, h: Hapi.ResponseObject) => {

        if (!req.params.userId) {
          throw Boom.badRequest();
        }

        return 200;
      }
    }});

So my test looks like this:

it('should return 200', async () => {
  const request : ServerInjectOptions = {
    url: '/user',
    method: 'POST',
    payload: {
      email: 'e@email.de',
      password: 'secred',
      firstname: 'John',
      lastname: 'Doe'
    },
    app: {}
  };

  const response = await server.inject(request);
  expect(response.statusCode).toEqual(200);
});

As you can see the route expects a param in the params array with the name userId but i am not able to set the parameter on the ServerInjectOptions object. The error I get is that the property does not exist on the ServerInjectOptions type.

Is there any other way i can set the params array? I didn`t find something in the docs maybe i missed it and someone can tell me where to find it.

Thanks in advance


Solution

  • For the route I believe you add the name of the parameter to the path like so:

    server.route(
      {
        method: 'POST',
        path: '/:userId', 
        //
        }});
    

    And for the test you should be able to add your parameter to the url option:

    const request : ServerInjectOptions = {
        url: '/user/parameterYouNeedToAdd',
        //
    };
    

    Or if the parameter is a variable:

    const request : ServerInjectOptions = {
        url: '/user/' + parameterYouNeedToAdd,
        //
    };