Mocha + Chai - 没有关于错误的详细信息
Mocha + Chai - no details on errors
我对 mocha 和 chai 有疑问。我的测试没有显示失败测试的错误(例如,预计 'a' 为 'b')。 test log
1) Shouldn't publish new post - there is a post with this title
npm ERR! Test failed. See above for more details.
示例代码:
it('Shouldn\'t publish new post - some required fields are empty', done => {
request(app)
.post('/posts')
.set('Authorization', `Bearer ${token}`)
.send()
.end((err, { body }) => {
if(err) {
return done(err);
}
expect(body).to.have.property('errors');
return done();
});
});
我认为问题不直接出在 mocha 或 chai 上。我的回购:github repository.
您需要做的就是克隆存储库、安装依赖项和 运行 mongodb。随意创建虚假测试并查看输出。
此致
问题是由于嵌套回调,错误处理不一致。如果 expect(body)...
断言失败,这将导致异步错误,该错误永远不会报告给使用 done(error)
的当前测试,因此所有异步 Chai 断言都应使用 try..catch
.
包装
更好的方法是使用 Mocha 原生支持的 promises,so does Supertest。这允许在没有 done
回调的情况下始终如一地处理错误:
it('Shouldn\'t publish new post - outdated/wrong token', async () => {
const { body } = await request(app)
.post('/posts')
.set('Authorization', 'Bearer blah_blah_blah')
.send();
expect(body).to.have.property('errors');
});
我对 mocha 和 chai 有疑问。我的测试没有显示失败测试的错误(例如,预计 'a' 为 'b')。 test log
1) Shouldn't publish new post - there is a post with this title
npm ERR! Test failed. See above for more details.
示例代码:
it('Shouldn\'t publish new post - some required fields are empty', done => {
request(app)
.post('/posts')
.set('Authorization', `Bearer ${token}`)
.send()
.end((err, { body }) => {
if(err) {
return done(err);
}
expect(body).to.have.property('errors');
return done();
});
});
我认为问题不直接出在 mocha 或 chai 上。我的回购:github repository.
您需要做的就是克隆存储库、安装依赖项和 运行 mongodb。随意创建虚假测试并查看输出。
此致
问题是由于嵌套回调,错误处理不一致。如果 expect(body)...
断言失败,这将导致异步错误,该错误永远不会报告给使用 done(error)
的当前测试,因此所有异步 Chai 断言都应使用 try..catch
.
更好的方法是使用 Mocha 原生支持的 promises,so does Supertest。这允许在没有 done
回调的情况下始终如一地处理错误:
it('Shouldn\'t publish new post - outdated/wrong token', async () => {
const { body } = await request(app)
.post('/posts')
.set('Authorization', 'Bearer blah_blah_blah')
.send();
expect(body).to.have.property('errors');
});