我一直在尝试在Angular 6的拦截器中运行测试单元,但是经过反复尝试,我仍然收到以下错误:
错误:预期对标准“按功能匹配:”的一个匹配请求,但未找到。
我是NG6和单元测试的新手,在文档中找不到任何内容
这就是我得到的:
令牌服务(由于与后端没有连接而被嘲笑)
export class TokenService {
token: EventEmitter<any> = new EventEmitter();
findTokenData(): Observable<any> {
return Observable.create((observer: Observer<object>) => {
observer.next({ headerName: x-fake, token: fake' });
observer.complete();
});
}
}
休息拦截器
export class RestInterceptor implements HttpInterceptor {
constructor(public tokenService: TokenService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('request intercepted...');
let authReq: HttpRequest<any>;
const customHeadersMethods = ['POST', 'PUT', 'DELETE', 'PATCH'];
// If the requested method is different GET or HEAD request the CSRF token from the service and add it to the headers
if (customHeadersMethods.indexOf(req.method) !== -1) {
this.tokenService.findTokenData().subscribe(res => {
authReq = req.clone({
headers: req.headers.set(res.headerName, res.token),
});
});
} else {
authReq = req.clone();
}
// send the newly created request
return next.handle(authReq);
}
}
其余拦截器规格
describe('RestInterceptor', () => {
const mockTokenService = {
headerName: 'x-fake',
token: 'fake'
};
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
{
provide: TokenService,
useValue: mockTokenService
},
{
provide: HTTP_INTERCEPTORS,
useClass: RestInterceptor,
multi: true
}]
});
});
afterEach(inject([HttpTestingController], (httpMock: HttpTestingController) => {
httpMock.verify();
}));
it('Should add a custom header', inject([HttpClient, HttpTestingController], (http: HttpClient, httpMock: HttpTestingController) => {
http.post('/data', {}).subscribe(
response => {
expect(response).toBeTruthy();
}
);
const req = httpMock.expectOne(r =>
r.headers.has(`${mockTokenService.headerName}`) &&
r.headers.get(`${mockTokenService.headerName}`) === `${mockTokenService.token}`);
expect(req.request.method).toEqual('POST');
httpMock.verify();
}));
});
谁能帮助我了解我在想什么?
最佳答案
我认为您错过了TokenService
不是简单值而是返回的类的事实。
这是发生了什么:
您定义了模拟:
const mockTokenService = {
headerName: 'x-fake',
token: 'fake'
};
覆盖它:
{
provide: TokenService,
useValue: mockTokenService
},
现在,Angular将使用此
findTokenData
对象作为mockTokenService
中注入的值,并...this.tokenService.findTokenData().subscribe(res => {
||
undefined => error
因此,您可以执行以下操作来解决此问题:
import { of } from 'rxjs';
...
const mockToken = {
headerName: 'x-fake',
token: 'fake'
};
const mockTokenService = {
findTokenData: () => {
return of(mockToken);
}
};
...
const req = httpMock.expectOne(r =>
r.headers.has(`${mockToken.headerName}`) &&
r.headers.get(`${mockToken.headerName}`) === `${mockToken.token}`);