如何在mocha-chai测试中的describe块的两个it块之间插入时间延迟?

时间:2019-04-23 11:28:48

标签: node.js mocha chai

我想在我的describe块的两个it()之间插入一个时间延迟。第二个it()将获取在某个时间段之间推送的数据。在执行第一个it()之前,我将time保留在time1变量中,然后使用下面的setTimeout函数通过发送time1和time2(结束时间)来执行下一个it()。

但是,第二个it()似乎没有按照我的要求运行。我需要如何更改它,或者有时间延迟调用第二个it()的方法是什么?

        var chai = require('chai');
        var chaiHttp = require('chai-http');    
        var should = chai.should();
        var expect = chai.expect;
        var http = require('http');
        chai.use(chaiHttp);
        var server;
        var mongodb;

        before(function (done) {
            server = require('../../../app.js'); // same as "node app.js"
            done();
        })

        after(function (done) {
            server.close();
        })

        describe('POST call to insert data into project', ()=> {
            var time1= new Date();
            time1 = time1.getTime();
            it('Creating project', (done) => {
                chai.request(server)
                .post('/create/myproject')
                .send()
                .end((err, res) => {
                    expect(res.statusCode).to.equal(200);
                    chai.request(server)
                    .post('/data/myproject')
                    .send(json_obj)
                    .end((err, res) => {
                         expect(res.statusCode).to.equal(200);
                         chai.request(server)
                         .get('/data/myproject')        
                         .end((err, res) => {
                             expect(res.statusCode).to.equal(200);
                         });
                    });
                    done();
                });
            });  //it    


            /* Below it() block should be executed after 30s with the time1 and 
               time2 variable */
            it("Doing total counting", (done) => {

             // this.timeout(30000);
             setTimeout(function () {
               var time2= new Date();
               time2 = time2.getTime();
               var url  = 'total?start_time=' + time1 + '&end_time=' + time2;
            chai.request(server)
                .get(url)
                .send()
                .end((err, res) => {
                    expect(res.statusCode).to.equal(200);

                    done();
                }
                )
        }, 30000)

    })     
});// describe

1 个答案:

答案 0 :(得分:1)

看起来您可以从built in this.timeout()功能中受益

        this.timeout(30000);

        it("Doing total counting", (done) => {             
           var time2= new Date();
           time2 = time2.getTime();
           var url  = 'total?start_time=' + time1 + '&end_time=' + time2;
        chai.request(server)
        ...    
        setTimeout(3000, done)