javascript - 使用 axios 对拦截器进行单元测试会引发错误
问题描述
我正在为我的 Nestapp 编写单元测试。对于拦截器文件,我正在编写一个测试用例以在何时抛出错误并使用错误消息进行error.message.indexOf('timeout') >= 0
调用。Axios.Cancel
但是在我的规范文件中,我得到: Cannot read property 'intercept' of undefined
PFB 我的代码,我在这里缺少什么?
如果需要,可以提供任何模拟!
timeout.interceptor.ts
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
直接使用,而是使用嵌套HttpService
。然后它变得更容易测试。
HttpService
您可以通过拦截器的构造函数注入:
export class TimeoutInterceptor implements NestInterceptor {
constructor(httpService: HttpService) {}
这使得测试变得更加容易,因为HttpService
当axios
您创建TimeoutInterceptor
.
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();
推荐阅读
- python - 检查存储在内存位置的数据大小
- java - 从基类和实例成员顺序初始化问题中调用的构造函数、子类方法
- c# - 基于日期和大小的 Log4Net 滚动
- tensorflow - 在 tf.Estimator 方法上禁用 TensorBoard 日志记录
- nfc - Teensy 3.5 上的 NFC PN532
- django - Django ckeditor - 将宽度设置为 100%
- reactjs - 在本机反应中增加 AsyncStorage 大小限制
- php - mysql查询到数组
- ios - 我可以更改我的应用在默认 iOS 共享表中的位置吗?
- antlr4 - ANTLR:如何使用 ANTLR 4 根据索引位置解析固定长度的文本文件?