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

相关内容

热门资讯

黑科技辅助挂(德州免费)wPk... 德州新手教程相关信息汇总(需添加指定威信136704302获取下载链接);黑科技辅助挂(德州免费)w...
黑科技脚本(Wepoke总结)... 黑科技脚本(Wepoke总结)轰趴十三水原本是真的有挂!太坑了果然真的是有挂(2023已更新)(哔哩...
黑科技攻略(微扑克模拟器)wp... 黑科技攻略(微扑克模拟器)wpk游戏原先是有挂!太嚣张了确实存在有挂(2025已更新)(哔哩哔哩);...
黑科技有挂(哈糖大菠萝洗牌)w... 黑科技有挂(哈糖大菠萝洗牌)wPk好像存在有挂!太嚣张了一直有挂(2026已更新)(哔哩哔哩);实战...
黑科技脚本(微扑克ai)Wep... 黑科技脚本(微扑克ai)WepokE确实存在有挂!太嚣张了本然真的是有挂(2020已更新)(哔哩哔哩...
黑科技私人局(aapoker辅... 黑科技私人局(aapoker辅助)AAPoKER真是是有挂!太嚣张了原来是有挂(2025已更新)(哔...
黑科技苹果版(Wepoke助手... 黑科技苹果版(Wepoke助手)wPK原生存在有挂!太实锤了竟然存在有挂(2024已更新)(哔哩哔哩...
黑科技代打(德扑之星模拟器)a... 黑科技代打(德扑之星模拟器)aapokEr固有真的是有挂!太夸张了一直是有挂(2025已更新)(哔哩...
辅助黑科技(aapoker教程... 辅助黑科技(aapoker教程)epoker先前是真的有挂!太夸张了起初真的有挂(2022已更新)(...
黑科技存在(微扑克ai)Wep... 黑科技存在(微扑克ai)WepokE确实存在有挂!太嚣张了总是真的是有挂(2023已更新)(哔哩哔哩...