Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 测试失败-摩卡咖啡&x27;s done()被多次调用_Javascript_Unit Testing_Callback_Mocha.js - Fatal编程技术网

Javascript 测试失败-摩卡咖啡&x27;s done()被多次调用

Javascript 测试失败-摩卡咖啡&x27;s done()被多次调用,javascript,unit-testing,callback,mocha.js,Javascript,Unit Testing,Callback,Mocha.js,我尝试过看一些有类似错误的主题,但无法将这些解决方案与我的问题结合起来 当我尝试运行以下测试时(包括测试的功能): 我得到这个错误: 这是什么原因,我如何修复它?您需要在myFunc的if块中添加一个return,以便只调用一次回调函数next,实际上是主测试用例中的done()回调: function myFunc(next, obj) { const pairs = {}; obj.listing.forEach((element) => { if (element.x

我尝试过看一些有类似错误的主题,但无法将这些解决方案与我的问题结合起来

当我尝试运行以下测试时(包括测试的功能):

我得到这个错误:
这是什么原因,我如何修复它?

您需要在
myFunc
if
块中添加一个
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();
}

@安基夫·阿加瓦尔的解决方案并不正确,但它确实为我指明了正确的方向

forEach()方法没有短路,因此多次调用next()

我能用两种方法之一解决这个问题

通过从forEach()逻辑提取对next()的调用:

但是,这仍然会使forEach()在所有元素中运行。如果可能的话,最好将其短路,并在出现设置错误的违规情况时立即断开,如下所示:

function myFunc(next, obj) {
  const pairs = {};
  const BreakException = {};
  let err = null;
  try {
    obj.listing.forEach((element) => {
      if (element.x in pairs && pairs[element.x] !== element.y) {
        err = new Error('This was not ok');
        throw BreakException;
      } else {
        pairs[element.x] = element.y;
      }
    });
    next();
  } catch (e) {
    if (e !== BreakException) throw e;
    next(err);
  }
}

希望将来有人能使用它。

我刚刚尝试了这个(也尝试了向两个调用添加一个返回到next()),但它仍然抛出相同的错误。你的回答确实把我推向了正确的方向。我刚刚发布了这个问题的解决方案。
function myFunc(next, obj) {
  const pairs = {};
  let err = null;
  obj.listing.forEach((element) => {
    if (element.x in pairs && pairs[element.x] !== element.y) {
      err = new Error('This was not ok');
    } else {
      pairs[element.x] = element.y;
    }
  });

  if (err !== null) {
    next(err);
  } else {
    next();
  }
}
function myFunc(next, obj) {
  const pairs = {};
  const BreakException = {};
  let err = null;
  try {
    obj.listing.forEach((element) => {
      if (element.x in pairs && pairs[element.x] !== element.y) {
        err = new Error('This was not ok');
        throw BreakException;
      } else {
        pairs[element.x] = element.y;
      }
    });
    next();
  } catch (e) {
    if (e !== BreakException) throw e;
    next(err);
  }
}