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

相关内容

热门资讯

第五分钟辅助!wepoker数... 第五分钟辅助!wepoker数据分析,wpk有那种辅助吗,练习教程(有挂细节)1、玩家可以在wpk有...
4分钟辅助!hhpoker辅助... 4分钟辅助!hhpoker辅助挂下载,hhpoker德州牛仔视频,诀窍教程(有挂神器)1、hhpok...
第3分钟辅助!wepoker祈... 第3分钟辅助!wepoker祈福有用吗,pokeplus脚本,绝活儿教程(真的有挂)1、起透看视 w...
第六分钟辅助!werplan脚... 第六分钟辅助!werplan脚本,aapoker怎么控制牌,技法教程(真的有挂)aapoker怎么控...
第六分钟辅助!德普之星怎么开辅... 第六分钟辅助!德普之星怎么开辅助,德州局脚本,讲义教程(有挂教学)亲,关键说明,德普之星怎么开辅助透...
一分钟辅助!hhpoker是真... 一分钟辅助!hhpoker是真的还是假的,红龙poker辅助平台,方式教程(有挂秘籍)1、hhpok...
第三分钟辅助!哈糖大菠萝万能挂... 第三分钟辅助!哈糖大菠萝万能挂,hhpoker的辅助是真的吗,资料教程(有挂方式)1、hhpoker...
6分钟辅助!wepoker透视... 6分钟辅助!wepoker透视有没有,wepokerplus万能挂,步骤教程(真的有挂)一、wepo...
第8分钟辅助!wepoker辅... 第8分钟辅助!wepoker辅助器是真的吗,wepoker透视脚本免费app,指引教程(真是有挂)1...
8分钟辅助!wepoker辅助... 8分钟辅助!wepoker辅助真的假的,wpk真吗,阶段教程(有挂方针)8分钟辅助!wepoker辅...