node.js - 使用 Supertest 进行测试时在 header 部分设置 Bearer Token

标签 node.js jestjs rest supertest ts-jest

我正在尝试在使用 Supertest 进行测试时在 POST 请求的 header 部分中添加承载。我尝试了很多方法。我是测试的初学者。请提出一些更好的方法来实现这一目标。

这是我的示例代码。这有什么问题吗?

it('POST/userAuth', async (done) => {
  const res = await request
                          .post('/v1/user/haha')
                          .set('Authorization', `bearer ${Token}`)
                          .send({
                            title: 'Some random text',
                            options: [
                              { start: hello, end: world },
                              { start: good, end: bye },
                            ],
                          });

最佳答案

您可以像这样设置请求 header :

const request = require('supertest');
const express = require('express');

const app = express();

const TOKEN = 'some_token';

describe('POST /some-url', function() {
  it('does something', function(done) {
    request(app)
      .post('/some-url')
      .send({ body: 'some-body' })
      .set('Authorization', `Bearer ${TOKEN}`)
      .expect(200, done);
  });
});

关于node.js - 使用 Supertest 进行测试时在 header 部分设置 Bearer Token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65856278/

相关文章:

unit-testing - Jest 无法转换 node_modules

javascript - enzyme 测试 React.createRef()

javascript - 语法错误 : Invalid or unexpected token when testing react application with babel and jest

jsf - 集成 Spring MVC 和 JSF 2.1

node.js - Node.js 可以为目录索引文件使用另一个文件名,而不是 `index.js` 吗?

javascript - 在 GoDaddy VPS Windows Plesk 上安装 Node.js

rest - REST API 错误消息是否应该国际化?

php - 使用 REST 在 PHP 中上传文件

javascript - 将 Node-cron 与 CoffeeScript 结合使用

javascript - Typescript 中的条件默认导出