将 supertest 与 jest 和 express 结合使用时,在请求 header 中设置身份验证令牌

Set an authentication token in a request header when using supertest with jest and express

我正在尝试测试我的 express 应用程序中受 jwt 中间件保护的路由。我试过在 beforeAll 调用中模拟获取 jwt 令牌的请求:

let token = "";
beforeAll((done) => {
    supertest(app)
        .get("/authentication/test")
        .end((err, response) => {
            console.log(response.body); // "fewiu3438y..." (successfully got token) 
            token = response.body.token; // Tried to update token variable with jwt token
            done();
        });
});
console.log(token); // "" (I haven't updated the token variable) 

因此,当我尝试 运行 后续测试时,我没有可在 headers:

中使用的有效身份验证令牌
    describe("Simple post test using auth", () => {
        test.only("should respond with a 200 status code", async () => {
            console.log({ POSTTest:token }); // "" still not set, so test will fail.
            const response = await supertest(app).post("/tests/simple").send();
            expect(response.statusCode).toBe(200);
        });
    });

有没有办法更新变量,或者使用 beforeAll 设置所有 headers?或者有什么我不知道的更好的方法吗?

尝试使用 async 函数作为 beforeAll 回调:

let token = '';

beforeAll(async () => {
  const response = await supertest(app).get('/authentication/test');
  token = response.body.token;
});

然后,使用set方法在测试中传递令牌:

describe('Simple post test using auth', () => {
  test.only('should respond with a 200 status code', async () => {
    const response = await supertest(app)
      .post('/tests/simple')
      .set('Authorization', `Bearer ${token}`);

    expect(response.statusCode).toBe(200);
  });
});

我是这样做的

    import * as request from 'supertest';

    describe('Simple post test using auth', () => {
    test.only('should respond with a 200 status code', async () => {
     const res = await request(app.getHttpServer())
      .post('/tests/simple')
      .send(payload)
      .set('Authorization', `Bearer ${token}`);

    expect(res.statusCode).toBe(200);
  });
});

我还建议您模拟您的身份验证请求。如果您使用的是开玩笑,这是类似的问题 Mock Authentication Request -Jest