如何在玩笑和打字稿中发出错误事件

时间:2018-12-19 15:13:23

标签: node.js typescript unit-testing jestjs

例如,我正在使用Archiver

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

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

1 个答案:

答案 0 :(得分:1)

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

@echo off & cls
:setnum
set /p %ynum%=Pick a Number: 
:start
echo This is your number: %ynum%
timeout /t 1 /nobreak > NUL
goto start

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

//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");