gpt4 book ai didi

node.js - 测试异步代码时如何检查 Mocha 中的断言错误

转载 作者:搜寻专家 更新时间:2023-10-31 22:19:40 25 4
gpt4 key购买 nike

当使用 Mocha 测试异步代码并且我的一个断言失败时,Mocha 所做的只是报告超时错误。有没有办法改善这个?如何知道什么断言失败以及原因?

mocha

Contact
#getContacts()
1) should return at least 1 contact


0 passing (3s)
1 failing

1) Contact #getContacts() should return at least 1 contact:
Error: timeout of 3000ms exceeded. Ensure the done() callback is being called in this test.

代码:

var assert         = require("assert");
var contact = require("../lib/contact.js");
var chai = require('chai');
var should = chai.should();

describe('Contact', function() {
describe('#getContacts()', function() {
it('should return at least 1 contact', function(done) {
contact.getContacts().then(function(contacts) {
assert.equal(4,2)

done()
});
})
})
});

最佳答案

问题是断言失败,抛出异常。这导致 promise 被拒绝,但没有人注意到。您的代码仅检查 promise 是否成功。如果您返回 promise,那么 mocha 将检查它,如果 promise 被拒绝,则测试失败。

所以你想要

it('should return at least 1 contact', function() {
return contact.getContacts().then(function(contacts) {
assert.equal(4,2);
});
});

关于node.js - 测试异步代码时如何检查 Mocha 中的断言错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30561345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com