Supertest / Jest检查标头是否存在

时间:2019-09-16 19:19:58

标签: node.js jestjs supertest

是否可以使用supertestjest检查响应中是否存在某些标头?

例如expect(res.headers).toContain('token')

2 个答案:

答案 0 :(得分:0)

这是解决方案,您可以使用.toHaveProperty(keyPath, value?)方法检查响应中是否存在某个标头。

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);
  });
});

覆盖率100%的集成测试结果:

 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

以下是完整的演示:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/57963177

答案 1 :(得分:0)

使用自定义断言方法的这种方法也是可行的,例如:

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());
});