AngularErrorInterceptor单元测试不如预期工作
创始人
2024-10-24 17:01:08
0
  1. 首先,确保在测试中正确导入需要测试的模块和服务类。

import { TestBed } from '@angular/core/testing'; import { ErrorInterceptor } from './error.interceptor'; import { HttpClientTestingModule } from '@angular/common/http/testing';

describe('ErrorInterceptor', () => { let errorInterceptor: ErrorInterceptor;

beforeEach(() => {
    TestBed.configureTestingModule({
        imports: [HttpClientTestingModule],
        providers: [ErrorInterceptor]
    });

    errorInterceptor = TestBed.inject(ErrorInterceptor);
});

});

  1. 创建模拟的http响应和错误。

const mockErrorResponse = { status: 404, statusText: 'Not Found' }; const mockError = new Error('Not Found');

  1. 创建测试用例并使用HttpClientTestingModule发送模拟的http请求和响应。

it('should intercept errors', () => { const httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']); httpClientSpy.get.and.returnValue(asyncError(mockErrorResponse));

const next: HttpHandler = {
    handle: req => {
        throw mockError;
    }
};

errorInterceptor.intercept(null, next).subscribe(
    () => fail('expected an error, not a successful result'),
    error => {
        expect(error).toEqual(mockErrorResponse);
    }
);

});

  1. 如果没有使用async和fakeAsync来测试异步代码,则需要使用jasmine-done函数来标记测试的完成。

it('should intercept errors', (done: DoneFn) => { const httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']); httpClientSpy.get.and.returnValue(asyncError(mockErrorResponse));

const next: HttpHandler = {
    handle: req => {
        throw mockError;
    }
};

errorInterceptor.intercept(null, next).subscribe(
    () => fail('expected an error, not a successful result'),
    error => {
        expect(error).toEqual(mockErrorResponse);
        done();
    }
);

});

使用这些步骤能够测试ErrorInterceptor拦截器。

相关内容

热门资讯

透视玄学!xpoker辅助怎么... 透视玄学!xpoker辅助怎么用,一向真的是有挂(透视)攻略教程(有挂插件);在进入xpoker辅助...
透视最新!wepoker透视方... 透视最新!wepoker透视方法,竟然是有挂(透视)wpk教程(有挂详情)1、wepoker透视方法...
透视能赢!pokermaste... 透视能赢!pokermaster辅助器,从前真的是有挂(透视)2025新版(有挂黑科技)1、操作简单...
透视黑科技!哈糖大菠萝开挂,竟... 透视黑科技!哈糖大菠萝开挂,竟然有挂(透视)靠谱教程(有挂细节)1、下载好哈糖大菠萝开挂辅助软件之后...
透视科技!wepoker私人局... 透视科技!wepoker私人局透视方法,都是真的有挂(透视)新2025教程(有挂方法)1、wepok...
透视黑科技!hhpoker哪个... 透视黑科技!hhpoker哪个俱乐部靠谱,都是真的有挂(透视)爆料教程(有挂攻略);1、构建自己的h...
透视app!pokemmo手机... 透视app!pokemmo手机脚本辅助器,竟然是有挂(透视)新2025版(有挂教程)1、pokemm...
透视脚本!wpk辅助哪里买,一... 透视脚本!wpk辅助哪里买,一贯存在有挂(透视)普及教程(有挂详情)1、wpk辅助哪里买系统规律教程...
透视安卓版!wepoker破解... 透视安卓版!wepoker破解器,本来真的有挂(透视)AI教程(有挂方法)1、操作简单,无需注册,只...
透视新版!wepoker怎么设... 透视新版!wepoker怎么设置房间,好像真的是有挂(透视)扑克教程(有挂插件);1、用户打开应用后...