[英]nodejs async await does not wait in test
我有一个 nodejs jest 测试,它失败了,因为它不等待Promise
。
it('returns an error if the ticket is already reserved', async () => {
const ticket = Ticket.build({
title: 'Concert',
price: 20
});
await ticket.save();
console.log('TICKET ID:', ticket.id);
const order = Order.build({
userId: 'asdasd',
status: OrderStatus.Created,
expiresAt: new Date(),
ticket
});
await order.save();
console.log('Order ID:', order.id);
await request(app)
.post('api/orders')
.set('Cookie', global.signin())
.send({
ticketId: ticket.id
})
.expect(400);
});
在控制器中,我的功能如下。
import mongoose from 'mongoose';
import { Ticket } from '../models/ticket';
router.post('/api/orders',
...,
async (req: Request, res: Response) => {
const { ticketId } = req.body;
//Find the ticket the user is trying to order in the database
const ticket = await Ticket.findById(ticketId);
console.log('TICKET IN REQUEST: ', ticket);
if (!ticket) {
throw new NotFoundError();
}
....
res.status(201).send(order);
});
export { router as newOrderRouter };
让我用简单的方式解释一下。 在测试中,我尝试在 mongoDB 中创建一个票证并请求我的 API 来查看是否创建了票证。
您可以在下面的console.log()
输出中看到。
console.log
TICKET IN REQUEST: null
at src/routes/new.ts:27:17
console.log
TICKET ID: 5f6c3c7fd8bc648884890dc3
at src/routes/__tests__/new.test.ts:27:13
console.log
Order ID: 5f6c3c7fd8bc648884890dc4
at src/routes/__tests__/new.test.ts:38:13
因此,如您所见,日志的顺序并不理想。 无需等待其他 mongoDB 保存操作完成即可调用 API。 猫鼬保存操作返回承诺。 所以它应该等待。 但我无法理解这个问题。 任何的想法?
@ahmet,这是因为您在解决承诺之前比较结果。 你应该在 promise.then 中使用 expect 或将 await 结果存储在一个变量中然后比较它(测试用例)
it('returns an error if the ticket is already reserved', async () => {
const ticket = Ticket.build({
title: 'Concert',
price: 20
});
await ticket.save();
console.log('TICKET ID:', ticket.id);
const order = Order.build({
userId: 'asdasd',
status: OrderStatus.Created,
expiresAt: new Date(),
ticket
});
await order.save();
console.log('Order ID:', order.id);
const result=await request(app)
.post('api/orders')
.set('Cookie', global.signin())
.send({
ticketId: ticket.id
});
result.expect(400);
//or this one
//request(app)
// .post('api/orders')
// .set('Cookie', global.signin())
// .send({
// ticketId: ticket.id
// }).then(result=>result.expect(400))
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.