【问题标题】:How i can use Mocha and Chai to make an Async Test for Endpoints created by Node?我如何使用 Mocha 和 Chai 对 Node 创建的端点进行异步测试?
【发布时间】:2021-06-14 22:30:20
【问题描述】:
describe('Notifications API', ()=>{

    /*Getting All Notification*/
    describe('getNotifications', ()=>{
      it('it should GET all the notifications', async () => {
          const result = await chai.request(app).get('/getNotifications');
          result.should.have.status(200);
        });
    });
})

【问题讨论】:

  • 我收到此错误消息“错误:超过 2000 毫秒的超时。对于异步测试和挂钩,请确保调用了“done()”;如果返回 Promise,请确保它解决了)"

标签: node.js asynchronous mocha.js chai


【解决方案1】:

您可以这样做以不使用async/await

describe('Notifications API', () => {
    /*Getting All Notification*/
    describe('getNotifications', () => {
        it('it should GET all the notifications', (done) => {
            chai.request(app)
                .get('/getNotifications').then(result => {
                    result.should.have.status(200);
                    done()
                }).catch(e => {
                    done(e)
                })
        });
    });

})

我还使用await 测试了您的代码,它可以正常工作。

it('Prueba', async () => {
    const result = await chai.request('https://stackoverflow.com').get('/');
    return result.should.have.status(200);
  })

确保您的 API 在 2 秒内返回数据并添加 return(尽管并非绝对必要)。

作为提示:不要将您的路径称为getNotifications,仅使用/notifications 更有意义。你使用的动词表示你想做什么,而不是路径。

您在请愿书中使用了get 动词,因此将get 添加到路径中是多余的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-19
    • 2017-06-20
    • 2017-02-18
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    相关资源
    最近更新 更多