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

标签 javascript jasmine jasmine-node

我有一个对象订阅了 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/

相关文章:

angularjs - 有没有办法可以改变 Jasmine 中文本输出的颜色?

javascript - 如何获取 jasmine-node 中错误的堆栈跟踪?

javascript - Google 自定义搜索 - 根据查询字符串进行搜索

javascript - 正则表达式:从这个到那个匹配,除非另一个字符位于中间

Angular Jest 或 Jasmine 测试 : How to Properly Spy/Mock a Static Object Called From Within a Tested Class?

angularjs - 将 Angular 2.21 升级到 2.25 时,Jasmine httpBackend 相关测试中断

javascript - 使用历史推送响应路由器导航

javascript - 无法理解 redux 形式的一些代码

angularjs - Karma 中 JASMINE_ADAPTER 和 ANGULAR_SCENARIO_ADAPTER 之间的区别