Jim*_*ode 5 javascript express supertest jestjs
express我正在尝试测试我的应用程序中受 jwt 中间件保护的路由。我尝试模拟请求以在调用中获取 jwt 令牌beforeAll:
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)
Run Code Online (Sandbox Code Playgroud)
因此,当我尝试运行后续测试时,我没有可在标头中使用的有效身份验证令牌:
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);
});
});
Run Code Online (Sandbox Code Playgroud)
有没有办法更新变量,或者使用 来设置所有标头beforeAll?或者有我不知道的更好的方法吗?
Luc*_*ini 15
尝试使用async函数作为beforeAll回调:
let token = '';\n\nbeforeAll(async () => {\n const response = await supertest(app).get('/authentication/test');\n token = response.body.token;\n});\nRun Code Online (Sandbox Code Playgroud)\n然后,使用set\xc2\xa0 方法在测试中传递令牌:
describe('Simple post test using auth', () => {\n test.only('should respond with a 200 status code', async () => {\n const response = await supertest(app)\n .post('/tests/simple')\n .set('Authorization', `Bearer ${token}`);\n\n expect(response.statusCode).toBe(200);\n });\n});\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
15318 次 |
| 最近记录: |