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

相关内容

热门资讯

5分钟辅助挂!潮汕汇破解版,w... 5分钟辅助挂!潮汕汇破解版,wepoker开挂事件,新版2025教程(有挂解惑)1、点击下载安装,插...
透视安装!wepoker私局代... 透视安装!wepoker私局代打,来玩app 德州 辅助,必备教程(有挂秘笈);透视安装!wepok...
辅助透视!德州局透视脚本免费版... 辅助透视!德州局透视脚本免费版下载手机版,aapoker发牌逻辑,微扑克教程(有挂秘诀);1、点击下...
三分钟辅助挂!边锋斗地主微信小... 三分钟辅助挂!边锋斗地主微信小程序插件,小程序牵手跑得辅助,技巧教程(竟然有挂)1、全新机制【软件透...
四分钟辅助挂!约战武汉辅助插件... 四分钟辅助挂!约战武汉辅助插件,捉住捣蛋鸡作弊码,爆料教程(果真有挂)1、系统规律教程、辅助透视等服...
透视系统!wepoker黑侠破... 透视系统!wepoker黑侠破解,wepoker私人局俱乐部辅助,德州教程(有挂教程)是一款可以让一...
八分钟辅助挂!人海大厅软件辅助... 八分钟辅助挂!人海大厅软件辅助,凑一桌游戏辅助2023,实用技巧(有挂分享)1、游戏颠覆性的策略玩法...
透视了解!hhpoker可以控... 透视了解!hhpoker可以控制牌,wepoker透视脚本是有挂,必赢方法(有挂攻略);透视了解!h...
三分钟辅助挂!内蒙麻将外卦神器... 三分钟辅助挂!内蒙麻将外卦神器下载,蜜瓜大厅可以装挂,存在挂教程(有挂分析)在进入辅助挂后,参与本局...
透视神器!wpk有作弊,wep... 透视神器!wpk有作弊,wepoker免费脚本咨询,2025教程(的确有挂)是一款可以让一直输的玩家...