Home > Back-end >  How to test `verify` of an express middleware in Jest
How to test `verify` of an express middleware in Jest

Time:02-14

I have a function which returns a middleware as such:

const jsonParser = () => {
  return express.json({
    limit: '5mb',
    verify: (req, res, buf) => {
      // If the incoming request is a stripe event,
      if (req.headers['some-header']) {
        httpContext.set('raw-body', buf.toString());
      }
    },
  });
};

I would like to test that the httpContext.setis indeed called when the some-header header is present.

My test:

describe('jsonParser middleware', () => {
  it('sets the http context', async () => {
    const req = {
      headers: {
        'some-header': 'some-sig',
        'content-type': 'application/json',
      },
      body: JSON.stringify({
        some: 'thing',
      }),
    };

    const res = {};
    const middleware = jsonParser();

    middleware(req, res, () => {});

    expect(httpContext.set).toHaveBeenCalled();
  });
});

I have no idea how to make the test run the function passed to verify. Express docs state that the content type should be json, but nothing more. Anyone that can point me in the right direction is highly appreciated.

Thank you.

CodePudding user response:

as mentioned in the comments i want to give you an example of an integration test which tests the header and jsonwebtoken. i am also using the express framework but i wrote my code in JS.

this is a test for creating a forumpost in a forum i built. a middleware is checking for the token of the user so this case could be similiar to yours.

const request = require('supertest');

test('create authorized 201', async () => {
  const forumCountBefore = await ForumPost.countDocuments();
  const response = await request(app)
    .post('/api/forumPosts')
    .set({
      Authorization: `Bearer ${forumUserOne.tokens[0].token}`,
      userData: {
        userId: forumUserOneId,
        email: '[email protected]',
        username: 'forum',
      },
    })
    .send(forumPost)
    .expect(201);
  expect(response.body.message).toBe('created forumPost');

  const forumCountAfter = await ForumPost.countDocuments();
  expect(forumCountBefore   1).toBe(forumCountAfter);
});

i am using mongoDB thats why i use ForumPost.countDocuments to count the amount of entries in the DB.

as you can see in the test i use supertest (imported as request) to send an http call. in the set block i set the authorization token. this causes the middleware to be executed in the integration test.

the test can only pass when the code of the middleware gets executed correctly so it should cover the code of your middleware.

  • Related