如何使用mocha chai测试异步服务器代码?

时间:2018-03-09 12:03:24

标签: node.js mocha asynchronous-javascript

在我的mocha-test套件中,我想测试一个在场景后面进行异步调用的功能。我怎么能等到异步调用结束?

例如,我做了两个背靠背发布的电话。第一个post调用也在内部进行异步调用,直到异步操作完成,第二个post调用才通过。

我需要以下任何一种:

1)在两个帖子调用之间加一个延迟,以确保第一个帖子中的异步部分完成。
2)重复进行第二次呼叫,直到它通过 3)或如何通过mocha-chai测试异步调用?

以下是示例:

describe('Back to back post calls with asynchronous operation', ()=> {

            it('1st and 2nd post', (done) => {
                chai.request(server)
                .post('/thisis/1st_post')
                .send()
                .end((err, res) => {
                 expect(res.statusCode).to.equal(200);

                 /* HERE I Need A Delay or a way to call                   
               the below post call may be for 5 times */                       

                 chai.request(server)
                .post('/thisis/second_post')
                .send()
                .end((err, res) => {
                 expect(res.statusCode).to.equal(200);


                });

                done();
                });
            });         

        });

有办法解决这个问题吗?请帮忙。

感谢。

1 个答案:

答案 0 :(得分:2)

为了使用mocha测试异步函数,您有以下可能性

  

仅在执行序列中的最后一次回调后才使用done

it('1st and 2nd post', (done) => {
  chai.request(server)
    .post('/thisis/1st_post')
    .send()
    .end((err, res) => {
      expect(res.statusCode).to.equal(200);

      /* HERE I Need A Delay or a way to call
    the below post call may be for 5 times */

      chai.request(server)
        .post('/thisis/second_post')
        .send()
        .end((err, res) => {
          expect(res.statusCode).to.equal(200);

          //call done only after the last callback was executed
          done();
        });
    });
});
  

使用承诺

使用done回调
describe('test', () => {
  it('should do something async', (done) => {
    firstAsyncCall
       .then(() => {
          secondAsyncCall()
            .then(() => {
              done() // call done when you finished your calls
            }
       })
  });
})

经过适当的重构后,您将获得类似

的内容
describe('test', () => {
  it('should do something async', (done) => {
    firstAsyncCall()
      .then(secondAsyncCall())
      .then(() => {
        // do your assertions
        done()
      })
      .catch(done)
  })
})
  

使用async await,更清洁

describe('test', () => {
  it('should do something async', async () => {
    const first = await firstAsyncCall()
    const second = await secondAsyncCall()

    // do your assertion, no done needed
  });
})

要记住的另一个时刻是运行mocha测试时的--timeout参数。默认情况下,mocha正在等待2000毫秒,当服务器响应较慢时,您应该指定更大的数量。

mocha --timeout 10000