Supertest/Jest 检查 header 是否存在

geo*_*per 5 node.js supertest jestjs

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

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

sli*_*wp2 4

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

\n\n

index.ts:

\n\n
import express from \'express\';\n\nconst app = express();\n\napp.get(\'/test-with-token\', async (req, res) => {\n  res.set(\'token\', \'123\');\n  res.sendStatus(200);\n});\n\napp.get(\'/test\', async (req, res) => {\n  res.sendStatus(200);\n});\n\nexport default app;\n
Run Code Online (Sandbox Code Playgroud)\n\n

index.spec.ts:

\n\n
import app from \'./\';\nimport request from \'supertest\';\n\ndescribe(\'app\', () => {\n  it(\'should contain token response header\', async () => {\n    const response = await request(app).get(\'/test-with-token\');\n    expect(response.header).toHaveProperty(\'token\');\n    expect(response.status).toBe(200);\n  });\n\n  it(\'should not contain token response header\', async () => {\n    const response = await request(app).get(\'/test\');\n    expect(response.header).not.toHaveProperty(\'token\');\n    expect(response.status).toBe(200);\n  });\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n
 PASS  src/stackoverflow/57963177/index.spec.ts\n  app\n    \xe2\x9c\x93 should contain token response header (33ms)\n    \xe2\x9c\x93 should not contain token response header (10ms)\n\n----------|----------|----------|----------|----------|-------------------|\nFile      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |\n----------|----------|----------|----------|----------|-------------------|\nAll files |      100 |      100 |      100 |      100 |                   |\n index.ts |      100 |      100 |      100 |      100 |                   |\n----------|----------|----------|----------|----------|-------------------|\nTest Suites: 1 passed, 1 total\nTests:       2 passed, 2 total\nSnapshots:   0 total\nTime:        3.226s, estimated 4s\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n