首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Supertest/Jest检查头部是否存在

Supertest/Jest检查头部是否存在
EN

Stack Overflow用户
提问于 2019-09-17 03:19:58
回答 2查看 3.5K关注 0票数 4

有没有办法使用supertestjest检查响应中是否存在某个标头

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

EN

回答 2

Stack Overflow用户

发布于 2019-09-20 11:09:08

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

index.ts

代码语言:javascript
复制
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

代码语言:javascript
复制
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%覆盖率的集成测试结果:

代码语言:javascript
复制
 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

票数 3
EN

Stack Overflow用户

发布于 2020-01-28 16:18:18

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

代码语言:javascript
复制
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());
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57963177

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档