gpt4 book ai didi

javascript - 使用 axios 对拦截器进行单元测试会抛出错误

转载 作者:行者123 更新时间:2023-11-30 19:37:08 26 4
gpt4 key购买 nike

我正在为我的 Nestapp 编写单元测试。对于拦截器文件,我正在编写一个测试用例,当 error.message.indexOf('timeout') >= 0 并调用 Axios.Cancel 时抛出错误错误信息。

但在我的规范文件中,我得到:无法读取未定义的属性“拦截”PFB 我的代码,我在这里遗漏了什么?

如果需要,可以提供任何模拟!

超时.拦截器.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();
}
}
超时.拦截器.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。这样测试就容易多了。

您可以通过拦截器的构造函数注入(inject) 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();

关于javascript - 使用 axios 对拦截器进行单元测试会抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55816450/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com