例如,我正在使用Archiver

archive.on('error', err => {
  if (typeof callback === 'function') {
    callback.call(this, err);
  } else {
    throw err;
  }
});


根据玩笑,发现了这些线。您如何发出此错误?模拟吗

最佳答案

您可以将回调移动到其他模块,然后将其导出,例如:

//calbacks.js

const errorCallback = callback => err => {
  if (typeof callback === 'function') {
    callback.call(this, err);
  } else {
    throw err;
  }
}

export {errorCallback} // es6 named export


然后,您可以将其导入到主文件中:

import { errorCallback } from "./callbacks.js" //path should be correct, this would work if you have both files in same directory

...

archive.on('error', errorCallback(callback)) //pass callback to curried function


您也可以将其导入spec并进行测试:

const spy = jest.fn()

errorCallback(fn)("error")
expect(spy).toBeCalledWith("error");


并测试回调不起作用时的情况:

expect(() => {
    errorCallback("notFunction")("error")
}).toThrow()

关于node.js - 如何在玩笑和 typescript 中发出错误事件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53854097/

10-11 11:29