我有一个对象订阅了 Uncaught Error 事件,我正在尝试测试它的行为。首先,我尝试使用 jasmine-node,但现在当我尝试使用 jasmine 时,我发现了麻烦。谁能帮帮我。
describe('Constructor tests', function () {
it('error is passed to the callback', function (done) {
const error = new Error("testError-0");
let errorHandler = new AllErrorHandler((arg1) => {
expect(arg1).toBe(error);
errorHandler.dispose();
done();
});
setTimeout(() => {
throw error;
}, 0)
});
提前致谢。
最佳答案
当 jasmine ./tests/alLErrorException.spec.js
命令运行时,我直接通过 jasmine 执行了这个工作。需要进行以下更改:
始终设置监听器,即使不应执行 _callback
。
constructor(callback, startListening = true) {
if (!callback) {
throw new Error("Missing callback function");
}
this._callback = callback;
this._listening = startListening;
this._setupEvents();
}
添加一个函数来拦截 uncaughtException
事件并在我们 _listening
时调用 _callback
:
_handler() {
if(this._listening) {
this._callback.apply(null, arguments);
}
}
删除 _setupEvents
中的所有其他 uncaughtException
事件处理程序:
_setupEvents(attatch = true) {
this._listening = attatch ? true : false;
if (attatch) {
if (typeof window !== "undefined") {
window.addEventListener("error", this._callback);
} else {
// Added this line
process.removeAllListeners('uncaughtException');
process.addListener('uncaughtException', this._handler.bind(this));
}
} else {
if (typeof window !== "undefined") {
window.removeEventListener("error", this._callback);
} else {
process.removeListener('uncaughtException', this._callback);
}
}
}
这是必需的,因为 jasmine 设置了它自己的 uncaughtException
处理程序并报告错误,即使该错误已被 AllErrorHandler
类捕获。
Here是带有所需更改的 AllErrorHandler 类的完整源代码的粘贴。
关于javascript - 测试适用于 jasmine-node,但不适用于 jasmine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47558584/