[英]Async/Await test with Jest not working in Node js
我正在嘗試在 Node 中使用 Jest 測試async
調用,如下所示:
it('testing to sign up feature', async (done) => {
await expect(request(app).post('/signUp', {body:{a:1, b:3}})).resolves.toBe('created successful')
});
但是,它會引發此錯誤:
expect(received).resolves.toBe(expected) // Object.is equality
Expected: "created successful"
Received: {"header": {"connection": "close", "content-length": "18", "content-type": "text/html; charset=utf-8", "date": "Fri, 03 Jul 2020 09:35:39 GMT"}, "req": {"data": undefined, "headers": {"user-agent": "node-superagent/3.8.3"}, "method": "POST", "url": "http://127.0.0.1:53456/signUp"}, "status": 200, "text": "created successful"}
70 |
71 | it('testing to sign up feature', async (done) => {
> 72 | await expect(request(app).post('/signUp', {body:{a:1, b:3}})).resolves.toBe('created successful')
|
我不確定我應該如何模擬 resolves.toBe 下的響應text
resolves.toBe...
編輯
試過這個
const response = await request(app).post('/signUp', {body:{a:1, b:3}})
expect(response).resolves.toEqual('created successful')
但這導致了同樣的錯誤
萬一它是相關的。 我的注冊 API 如下所示:
signUp(req, res) {
log.info('User signed up request received');
postRequest('/signUp', JSON.stringify(req.body)).then((resp) => {
res.status("200").send(resp);
});
}
async function postRequest(path, param) {
try {
return await mockCall(path, param);
} catch (err) {
throw err;
}
}
function mockCall(path, param) {
// A mimic
const magicNumber = 2000;
return new Promise((resolve) => {
setTimeout(() => {
resolve("created successful");
}, magicNumber);
});
}
request(app).post('/signUp', {body:{a:1, b:3}})
是一個 promise,它返回一個 object。 您可以斷言.text
,而不是整個 object:
it('testing to sign up feature', async (done) => {
const response = await request(app).post('/signUp', {body:{a:1, b:3}})
expect(response.text).toBe('created successful')
});
我就是這樣解決的。
it('testing to sign up feature', async (done) => {
const f = await request(app)
.post('/signUp')
.send({body:{a:1, b:3}});
expect(JSON.parse(f.text)).toEqual({ message: 'user created successfully', status: 200 });
done();
});
此外,值得注意的是我使用npm-nock
來模擬調用。
beforeEach(() => {
nock(<url>)
.post('/signUp')
.reply(200, { message: 'user created successfully', status: 200})
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.