2017-05-05 77 views
0

我正在编写一个单元测试来测试我的postgres模式。我使用node-pg,mocha,sinon和chai。当失败时测试不会调用done()

这工作 - 测试通过没有问题:

describe('When adding a user',()=> { 
    it('should reject since email is used somewhere else', (done)=> { 
    pool.query(`INSERT INTO users(email, id, token) 
       VALUES($1, $2, $3)`, ['[email protected]', '12346', 'fooToken']) 
    .then((result)=> { 
     console.log('nothing in here runs, you will not see this'); 
     done() 
    }) 
    .catch((result) => { 
     result.constraint.should.have.string('email_already_exists'); 
     done(); 
    }) 
    }) 
}); 

但是,为了确保我没有得到一个误报,我改变断言到result.constraint.should.not.have.string('email_already_exists');故意使测试失败。

而不是测试失败,我得到Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.

我在做什么?

+1

如果您正在测试基于承诺的代码,您应该考虑使用Mocha的内置[promises支持](https://mochajs.org/#working-with-promises)。更容易防止这样的问题。 – robertklep

+0

@robertklep这个承诺如何支持在节点中测试2次读取? http://stackoverflow.com/questions/43690868/how-to-assert-stubbed-fetch-more-than-once/43806205#43806205 – dman

+1

一个很好的例子:https://coderwall.com/p/axugwa/cleaning-这个问题中的数据库之间的摩卡测试与pg-promise –

回答

1

如果你还是想用承诺这一点,问题是,在承诺未处理的异常不幸的是没有传播,而是被忽略。因此,没有人呼叫摩卡的done方法,导致超时。

如文档here所示,将侦听器附加到Node的unhandledRejection事件应该证明这一点。

如果您修改的原始代码和呼叫添加到无极的done方法(这不是摩卡的done方法!),那么你就可以捕获所有的错误,并通过他们向摩卡的done方法:

it('tests something', done => { 
    pool.query('...') 
    .then(result => { 
     // ... 
    }) 
    .catch(result => { 
     // assertion that fails 
    }) 
    .done(result => {}, error => { done(error); }); 
}); 

请注意,Promise.done()还不是标准的一部分,但仍受许多实现的支持。例如参见here

0

答:

的承诺链节点-PG导致期间测试这个奇怪的问题。如果我关闭回调的工作,那么没有问题:

describe('When adding a user',()=> { 
    it('should reject since email is used somewhere else', (done)=> { 
    function callback(err, result) { 
     err.constraint.should.not.have.string('email_already_exists'); 
     done(); 
    } 
    pool.query(`INSERT INTO users(email, id, token) 
       VALUES($1, $2, $3)`, ['[email protected]', '12346', 'fooToken'], callback) 
    }) 
}); 
相关问题