在Mocha中使用setTimeout()函数

时间:2019-03-08 04:28:57

标签: node.js unit-testing asynchronous mocha

我正在尝试在单元测试中使用setTimeout回调函数。基本上,执行测试后,需要等待2秒钟才能执行以下测试。但是,执行时出现此错误:

  Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

这是我的代码:

function delay(seconds,callback) {
    setTimeout(callback, seconds*1000);
}

describe('/REGISTER users', () => {
    it('should not REGISTER a user without a fullname field', (done) => {
            console.log('Starting delays');
            delay(2, () => {
                console.log('Two seconds delayed');
                let user = {
                    email: 'nilesh_maharjan@gmail.com',
                    password: 'abcdefghij'
                }
                chai.request(server)
                .post('/api/register')
                .send(user)
                .end((err, res) => {
                    res.should.have.status(422);
                    res.body.should.be.a('object');
                    res.body.should.not.have.property('fullname');
                    done(); 
                });
            });           
    });

    it('should REGISTER a user', (done) => {
        console.log('Starting delays');
        delay(2, () => {
            console.log('Two seconds delayed');
            let user = {
                email: 'mjn.nileshabcd@gmail.com',
                password: 'abcdefghij',
                fullname: 'Nilesh Maharjan'
            }
            chai.request(server)
            .post('/api/register')
            .send(user)
            .end((err, res) => {
                res.should.have.status(201);
                res.body.user.should.have.property('email');
                done();
            });
        });        
    });
});

0 个答案:

没有答案