【问题标题】:test works with jasmine-node, but not and with jasmine测试适用于 jasmine-node,但不适用于 jasmine
【发布时间】:2017-11-29 17:37:58
【问题描述】:

我有一个订阅了未捕获错误事件的对象,我正在尝试测试它的行为。首先我尝试使用 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)
});

提前致谢。

【问题讨论】:

  • 如果有人想详细了解我要测试的内容,这里是回购的link
  • 您遇到的具体问题是什么?
  • 除了 jasmine-node 之外,我无法编写测试以通过其他方式
  • 确切的错误信息是什么?
  • @WalleCyril 和茉莉一起跑步我明白了 - Failures: 1) Constructor tests error is passed to the callback Message: Error: testError-0 Stack: Error: testError-0 at UserContext.<anonymous> (C:\Users\jkanc\Desktop\all-error-handler\tests\allErrorException.spec.js:5:23)

标签: javascript jasmine jasmine-node


【解决方案1】:

jasmine ./tests/alLErrorException.spec.js 命令运行时,当我直接通过茉莉花执行时,我得到了这个工作。需要进行以下更改:

始终设置侦听器,即使不应执行 _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 类捕获。

Here 是 AllErrorHandler 类的完整源代码的粘贴,其中包含所需的更改。

【讨论】:

  • 首先,感谢您给我的建议和回答。但是为了通过一些测试而删除所有未捕获的异常监听器不是错的吗?有没有一种做法可以让我们说添加一个删除所有侦听器并仅在茉莉花工作时调用它的函数?
  • @JordanKanchelov 我会说这是错误的。更详细的方法将涉及检索现有处理程序的列表并可能调用它们。如果你这样做,jasmine 将在测试中报告错误。另外,IMO,这超出了这个问题的范围。
  • 您的解决方案有效,但我正在寻找一种方法来做到这一点,如果其他人找到另一种方法或框架来绕过它,我将暂时保留接受答案,因为不需要删除侦听器行为,并可能破坏任何其他用户逻辑。
  • 看看这个nodejs.org/api/events.html#events_emitter_listeners_eventname和这个nodejs.org/api/…。您可以使用 prependListener 在其他侦听器之前添加您的侦听器。或者您可以获取现有的侦听器并自己手动调用它们。
猜你喜欢
  • 2019-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-24
  • 2011-09-04
  • 1970-01-01
  • 2019-12-30
  • 2014-05-25
相关资源
最近更新 更多