【发布时间】:2017-10-04 09:52:54
【问题描述】:
我正在编写一个单元测试来测试我的 postgres 架构。我正在使用 node-pg、mocha、sinon 和 chai。
这行得通 - 测试通过,没有问题:
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)`, ['foo@email.com', '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.,而不是测试失败。
我得到了什么?
【问题讨论】:
-
如果您正在测试基于 Promise 的代码,您应该考虑使用 Mocha 的内置 promises support。预防此类问题要容易得多。
-
@robertklep 如何在节点中测试 2 次获取时使用此承诺支持? stackoverflow.com/questions/43690868/…
-
一个很好的例子:coderwall.com/p/axugwa/…
-
@dman 在那个问题中,您从一开始就不能很好地测试的代码开始。例如,
index.js运行的代码不会以任何方式暴露给“外部世界”。 -
@dman 见this gist。
标签: node.js postgresql unit-testing mocha.js chai