我曾尝试查看具有类似错误的主题,但无法将这些解决方案纳入我的问题的上下文中。
当我尝试运行以下测试时(包含已测试的功能):
function myFunc(next, obj) {
const pairs = {};
obj.listing.forEach((element) => {
if (element.x in pairs && pairs[element.x] !== element.y) {
const err = new Error('This was not ok');
next(err);
} else {
pairs[element.x] = element.y;
}
});
next();
}
it('should fail as 9 has been changed to 5 in the second object of the listing', function (done) {
const callback = (err) => {
if (err && err instanceof Error && err.message === 'This was not ok') {
// test passed, called with an Error arg
done();
} else {
// force fail the test, the `err` is not what we expect it to be
done(new Error('Assertion failed'));
}
}
myFunc(callback, {
"listing": [
{ "x": 5, "y": 9 },
{ "x": 5, "y": 11 }
]
});
});
最佳答案
您需要在 myFunc
的 if
block 中添加一个 return
以便回调函数 next
只被调用一次,实际上是主测试用例中的 done()
回调:
function myFunc(next, obj) {
const pairs = {};
obj.listing.forEach((element) => {
if (element.x in pairs && pairs[element.x] !== element.y) {
const err = new Error('This was not ok');
return next(err);
} else {
pairs[element.x] = element.y;
}
});
next();
}
关于javascript - 测试失败 - 多次调用 Mocha 的 done(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58638719/