【问题标题】:Testing NGXS exceptions with jasmine用 jasmine 测试 NGXS 异常
【发布时间】:2019-11-18 17:24:47
【问题描述】:

我正在尝试为我们的 Angular 应用程序通过 ngxs 执行的操作编写单元测试。在我的一项测试中,我希望该操作会引发错误。我尝试使用

expect(function() {store.dispatch(new MyAction(param));}).toThrowError();

但它给了我消息“预期函数会引发错误”。即使我在控制台中看到错误。在这次失败之后,我尝试了以下方法:

let errorMessage;
try {
    store.dispatch(new MyAction(param));
} catch (error) {
    console.log("In catch!");
    errorMessage = error;
}
expect(errorMessage).toBe(myErrorMessage);

我再次在控制台中看到错误,但没有看到“正在捕获!” console.log 在我的 catch 子句中。经过一番研究,我发现 angular 有它自己的 ErrorHandler,它在 jasmine 可以用它做某事之前捕获这个错误。如何防止这种情况发生?

【问题讨论】:

    标签: angular jasmine ngxs


    【解决方案1】:

    答案是:使用 jasmine 模拟 angular ErrorHandler!首先创建一个间谍:

    export const errorHandlerSpy = () => jasmine.createSpyObj('ErrorHandler', {
        handleError: undefined
    });
    

    在你的测试中使用这个间谍作为提供者:

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [NgxsModule, /*other imports*/],
            providers: [
                { provide: ErrorHandler, useFactory: errorHandlerSpy }
            ]
        }).compileComponents();
    }));
    

    检查抛出的错误是这样的:

    const errorHandler = TestBed.get(ErrorHandler);
    store.dispatch(new MyAction(param));
    expect(errorHandler.handleError).toHaveBeenCalledWith(new Error('Your error message'));
    

    我希望我避免了其他人解决这个问题的麻烦!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-07
      • 2016-06-16
      • 1970-01-01
      • 2020-08-03
      • 1970-01-01
      • 2012-08-19
      • 1970-01-01
      • 2013-06-28
      相关资源
      最近更新 更多