我正在嘗試測驗我的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)
因此,當我嘗試運行后續測驗時,我沒有可在標頭中使用的有效身份驗證令牌:
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? 或者有沒有我不知道的更好的方法?
uj5u.com熱心網友回復:
嘗試使用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);
});
});
uj5u.com熱心網友回復:
我這樣做
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);
});
});
另外,我建議您模擬身份驗證請求。如果您使用的是 jest Mock Authentication Request -Jest,這里有類似的問題
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/343852.html
標籤:javascript 表达 玩笑 超级测试
