简体   繁体   English

nodejs async await 在测试中不等待

[英]nodejs async await does not wait in test

I've a nodejs jest test and it fails because it does not wait Promise .我有一个 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);

});

In the controller I've function like below.在控制器中,我的功能如下。

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 };

Let me explain in a simple way.让我用简单的方式解释一下。 In test, I try to create a ticket in mongoDB and request my API to see ticket is created or not.在测试中,我尝试在 mongoDB 中创建一个票证并请求我的 API 来查看是否创建了票证。

You can see in console.log() outputs below.您可以在下面的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

So as you can see the order of logs are not in desired.因此,如您所见,日志的顺序并不理想。 API is called without waiting the other mongoDB save operations finish.无需等待其他 mongoDB 保存操作完成即可调用 API。 Mongoose save operation returns promise.猫鼬保存操作返回承诺。 So it should wait.所以它应该等待。 But I couldn't understand the problem.但我无法理解这个问题。 Any idea?任何的想法?

@ahmet, this is because you are comparing results before promise is resolved. @ahmet,这是因为您在解决承诺之前比较结果。 you should use expect in promise.then or store await result in a variable then compare it (test case)你应该在 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM