5

Is there a way to check if a certain header exists in the response using supertest and jest?

e.g expect(res.headers).toContain('token')

georgesamper
  • 4,989
  • 5
  • 40
  • 59

2 Answers2

4

Here is the solution, you can use .toHaveProperty(keyPath, value?) method to check if a certain header exists in the response.

index.ts:

import express from 'express';

const app = express();

app.get('/test-with-token', async (req, res) => {
  res.set('token', '123');
  res.sendStatus(200);
});

app.get('/test', async (req, res) => {
  res.sendStatus(200);
});

export default app;

index.spec.ts:

import app from './';
import request from 'supertest';

describe('app', () => {
  it('should contain token response header', async () => {
    const response = await request(app).get('/test-with-token');
    expect(response.header).toHaveProperty('token');
    expect(response.status).toBe(200);
  });

  it('should not contain token response header', async () => {
    const response = await request(app).get('/test');
    expect(response.header).not.toHaveProperty('token');
    expect(response.status).toBe(200);
  });
});

Integration test result with 100% coverage:

 PASS  src/stackoverflow/57963177/index.spec.ts
  app
    ✓ should contain token response header (33ms)
    ✓ should not contain token response header (10ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.ts |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        3.226s, estimated 4s

Here is the completed demo: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/57963177

Lin Du
  • 88,126
  • 95
  • 281
  • 483
0

This approach with custom assertion method is also possible, for example:

it("POST should redirect to a test page", (done) => {
    request(app)
        .post("/test")
        .expect(302)
        .expect(function (res) {
            if (!("location" in res.headers)) {
                throw new Error("Missing location header");
            }
            if (res.headers["location"] !== "/webapp/test.html") {
                throw new Error("Wrong location header property");
            }
        })
        .end((error) => (error) ? done.fail(error) : done());
});
zygimantus
  • 3,649
  • 4
  • 39
  • 54