我正在尝试用Jest in Node测试一个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')
|
我不确定如何在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);
});
}
答案 0 :(得分:0)
request(app).post('/signUp', {body:{a:1, b:3}})
是返回一个对象的承诺。您可以在.text
而不是整个对象上声明:
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')
});
答案 1 :(得分:0)
这就是我解决的方式。
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})
})