测试适用于 jasmine-node,但不适用于 jasmine

test works with jasmine-node, but not and with jasmine

我有一个对象订阅了未捕获的错误事件,我正在尝试测试它的行为。首先,我尝试使用 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 事件并调用 _callback 如果我们是 _listening:

_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 class.

捕获

Here 是 AllErrorHandler class 的完整源代码的粘贴,并进行了必要的更改。