[英]unit testing the interceptor with axios throws error
我正在為我的 Nestapp 編寫單元測試。 對於攔截器文件,我正在編寫一個測試用例以在error.message.indexOf('timeout') >= 0
時拋出錯誤並使用錯誤消息調用Axios.Cancel
。
但在我的規范文件中,我得到: Cannot read property 'intercept' of undefined
PFB 的Cannot read property 'intercept' of undefined
我的代碼,我在這里遺漏了什么?
如果需要,可以提供任何模擬!
import {
Injectable,
NestInterceptor,
CallHandler,
HttpCode
} from '@nestjs/common';
import {
Observable
} from 'rxjs';
import Axios from 'axios';
@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
intercept(context: any, next: CallHandler): Observable <any> {
const CancelToken = Axios.CancelToken;
const source = CancelToken.source();
const url: string = context.url ? context.url : context.args[0].url;
Axios.defaults.timeout = 200;
Axios.get(url, {
cancelToken: source.token
}).then((res) => {}, error => {
if (error.message.indexOf('timeout') >= 0) {
throw new Axios.Cancel('Operation canceled due to timeout!');
}
}).catch((error) => {
if (Axios.isCancel(error)) {
console.log('Request canceled ', error);
} else {
console.log('--else part--');
}
});
return next.handle();
}
}
timeout.interceptor.spec.ts
import { Test, TestingModule } from '@nestjs/testing'; import { HttpModule, Controller, ExecutionContext, Get, InternalServerErrorException } from '@nestjs/common'; import { of , Observable, throwError } from 'rxjs'; //import { Reflector } from '@nestjs/core'; import Axios from 'axios'; describe('Content Service', () => { let module: TestingModule; //let reflector; let timeoutInterceptor; //const loggerSpy = jest.fn() let getSpy; let cancelSpy; const errCode = 'MockController#decorated'; const errMessage = 'Controller threw an error'; beforeEach(async () => { module = await Test.createTestingModule({ imports: [HttpModule], }).compile(); getSpy = jest.spyOn(Axios, 'get'); timeoutInterceptor = new timeoutInterceptor(); }) it('should call Axios.Cancel when it catches an timeout>0', done => { const context = { url: '' } timeoutInterceptor.intercept(context, throwError(new InternalServerErrorException())) .subscribe( () => {}, () => { expect(Axios.Cancel).toHaveBeenCalled(); done(); } ) .unsubscribe(); }); });
您不應該直接使用axios
,而應該使用 nest 的HttpService
。 然后它變得更容易測試。
您可以通過攔截器的構造函數注入HttpService
:
export class TimeoutInterceptor implements NestInterceptor {
constructor(httpService: HttpService) {}
這使得測試變得更加容易,因為當您創建TimeoutInterceptor
的實例時,您可以使用HttpService
的模擬(它只是axios
的包裝器)。
const httpMock = jest.fn(() => ({
get: jest.fn(),
}))();
const interceptor = new TimeoutInterceptor(httpMock);
// mocked response
httpMock.get.mockReturnValue({...});
expect(interceptor.intercept(...)).toBe({...});
expect(httpMock.get).toHaveBeenCalled();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.