提问者:小点点

如何使用Mocha和Chai对node创建的endpoint进行异步测试?


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

共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动词,所以redundat将get添加到path中。

相关问题