gpt4 book ai didi

node.js - 如何在 Jest 和 typescript 中发出错误事件

转载 作者:太空宇宙 更新时间:2023-11-04 00:02:56 25 4
gpt4 key购买 nike

例如,我正在使用 Archiver :

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

这些台词是根据 Jest 揭开的。你怎么能发出这个错误呢?模拟?

最佳答案

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

//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 - 如何在 Jest 和 typescript 中发出错误事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53854097/

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