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拦截器。

相关内容

热门资讯

红龙扑克辅助工具!红龙扑克有没... 1、红龙扑克辅助工具!红龙扑克有没有外卦挂,(红龙扑克)确实是真的有挂(详细辅助挂教程)。2、透视辅...
wepoke智能ai!wepo... 此外,数据分析德州(wepoke智能ai)辅助神器app还具备辅助透视行为开挂功能,通过对客户wep...
智星德州菠萝辅助器!德扑助手,... 智星德州菠萝辅助器!德扑助手,德扑ai软件总是是真的有挂(详细房间设置教程)是一款可以让一直输的玩家...
wepoke辅助有挂!wepo... wepoke辅助有挂!wepoke管理员(wepoke好牌)好像真的有挂(详细有挂教程)1、让任何用...
aapoker透明挂!aapo... aapoker透明挂!aapoker到底有挂吗,(aapoker模拟器)好像真的有挂(详细有挂教程)...
智星德州菠萝外卦挂!德扑之星的... 智星德州菠萝外卦挂!德扑之星的发牌是不是有问题,德扑网上设置其实是真的有挂(详细ai教程)准备好在智...
德扑工具!德扑牌型胜率,德扑自... 德扑工具!德扑牌型胜率,德扑自定义房间总是真的有挂(详细猫腻教程)1、每一步都需要思考,不同水平的挑...
德扑之星猫腻!德扑之星数据解析... 德扑之星猫腻!德扑之星数据解析,德扑之星解析真是是真的有挂(详细电脑教程);wpk透视辅助官方版是专...
微扑克辅助挂!微扑克发牌规律性... WePoker透视辅助工具核心要点解析‌,微扑克辅助挂!微扑克发牌规律性,(微扑克苹果版)确实是有挂...
微扑克系统发牌规律!微扑克小程... 此外,数据分析德州(微扑克系统发牌规律)辅助神器app还具备辅助透视行为开挂功能,通过对客户微扑克系...