我正在尝试为适配器服务中的特定get
函数创建一个否定测试用例,该服务需要从服务器请求数据并做出相应的响应。该函数向服务器发送一个http get
请求,该请求返回所需的指定数据。为此,我使用HttpTestingController
向后端创建了一个模拟请求。到目前为止,我已经能够完成最明显的测试用例:返回200 / OK状态并向用户显示一些信息。
但是,当我谈到否定测试用例时,我正在尝试使用ErrorEvent
从后端创建错误。但是,当我运行测试时,它给我一个错误茉莉花失败:[object ErrorEvent] 。我知道对于不同的用户有很多类似的情况,当他们使用--source-map=false
时,许多情况已经解决了,但是对我来说,即使应用它也只显示相同的错误并带有堆栈跟踪。我一直试图弄清楚这一点,但不明白我在做什么错。
请在 adapter.service.spec.ts
中查看第二个get
测试
注意:我在应用程序中使用打字稿2.9.1和angular 6.0.8
以下是我用于测试的文件:
adapter.service.ts
import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';
import {
HttpHeaders,
HttpClient,
HttpParams,
} from '@angular/common/http';
import { Request, RequestOptions, Headers } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { JwtService } from '../jwt/jwt.service';
import { LoggerService } from '../logger/logger.service';
const API_URL = environment.api.host;
@Injectable({
providedIn: 'root'
})
export class AdapterService {
constructor(private http: HttpClient,
private jwtService: JwtService,
private logger: LoggerService) {}
/**
* This method logs the errors if the API call fails.
*
* @param self
* @method formatErrors
* @return
*/
private formatErrors(error: any) {
return throwError(error.error);
}
/**
* This method adds the headers to the API requests.
*
* @param path
* @method requestHeaders
* @return
*/
private requestHeaders(path: string) {
let headers;
if (path !== 'outh2/token') {
headers = new HttpHeaders({
'Accept': 'application/json',
'Oauth-Token': this.jwtService.getToken()
})
}
return headers;
}
/**
* This method generates the GET api call.
*
* @param path
* @param params
* @method get
* @return
*/
get(path: string, params: HttpParams = new HttpParams()): Observable < any > {
let headers = this.requestHeaders(path);
return this.http.get(`${API_URL}${path}`, { headers })
.pipe(catchError(this.formatErrors));
}
/**
* This method generates the PUT api call.
*
* @param path
* @param body
* @method put
* @return
*/
put(path: string, body: Object = {}): Observable < any > {
return this.http.put(
`${API_URL}${path}`,
JSON.stringify(body),
).pipe(catchError(this.formatErrors));
}
/**
* This method generates the POST api call.
*
* @param path
* @param body
* @method post
* @return
*/
post(path: string, body: Object = {}): Observable < any > {
return this.http.post(
`${API_URL}${path}`,
JSON.stringify(body),
).pipe(catchError(this.formatErrors));
}
/**
* This method generates the DELETE api call.
*
* @param path
* @method delete
* @return
*/
delete(path): Observable < any > {
return this.http.delete(
`${API_URL}${path}`,
).pipe(catchError(this.formatErrors));
}
}
adapter.service.spec.ts
import { TestBed, async, inject } from '@angular/core/testing';
import { HttpClientModule, HttpRequest, HttpParams } from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { environment } from '../../../environments/environment';
const API_URL = environment.api.host;
var PATH = 'somePATH';
import { AdapterService } from './adapter.service';
describe('AdapterService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientModule,
HttpClientTestingModule
],
providers: [
AdapterService
]
});
});
afterEach(inject([HttpTestingController], (backend: HttpTestingController) => {
backend.verify();
}));
//test case for GET
it('Send a valid GET request to the server', async(inject([AdapterService, HttpTestingController],
(service: AdapterService, backend: HttpTestingController) => {
let response = { "data": "answer" };
service.get(PATH).subscribe((next) => {
expect(next).toEqual(response);
});
backend.expectOne(API_URL + PATH).flush({ "data": "answer" }, { status: 200, statusText: 'Ok' });
})));
//THIS IS THE TEST CASE NOT WORKING FOR ME
it('Use an invalid or non existent URL to send the GET request', async(inject([AdapterService, HttpTestingController],
(service: AdapterService, backend: HttpTestingController) => {
service.get(PATH).subscribe((next: any) => {
expect(next.failure.error.type).toBe("URL not found!");
});
let responseFromServer = backend.expectOne(API_URL+PATH);
responseFromServer.error(new ErrorEvent("URL not found!"));
})));
//test case for POST
it('should send a valid POST request', async(inject([AdapterService, HttpTestingController],
(service: AdapterService, backend: HttpTestingController) => {
let data = { 'name': 'Admin', "class": "Superior" };
service.post(PATH, data).subscribe((next) => {
expect(next).toBeNull();
});
backend.expectOne(API_URL + PATH, JSON.stringify(data)).flush(null, { status: 200, statusText: 'Ok' });
})));
//test case for PUT
it('should send a valid PUT request', async(inject([AdapterService, HttpTestingController],
(service: AdapterService, backend: HttpTestingController) => {
let data = { 'name': 'MEME', "class": "NONE" };
service.put(PATH, data).subscribe((next) => {
expect(next).toBeTruthy();
});
backend.expectOne(API_URL + PATH, JSON.stringify(data)).flush(1, { status: 200, statusText: 'Ok' });
})));
//test case for DELETE
it('should send a valid DELETE request', async(inject([AdapterService, HttpTestingController],
(service: AdapterService, backend: HttpTestingController) => {
PATH = PATH + '/132';
service.delete(PATH).subscribe((next) => {
expect(next).toBeTruthy();
});
backend.expectOne(API_URL + PATH).flush(1, { status: 200, statusText: 'Ok' });
})));
});
我在Chrome上看到的错误
Error: Failed: [object ErrorEvent]
at stack (http://localhost:9876/absolute/var/www/html/employee_portal/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?73bc53d3671677e6a093fc74e4f9bcde57e5f7ad:2338:17)
at buildExpectationResult (http://localhost:9876/absolute/var/www/html/employee_portal/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?73bc53d3671677e6a093fc74e4f9bcde57e5f7ad:2308:14)
at Spec.expectationResultFactory (http://localhost:9876/absolute/var/www/html/employee_portal/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?73bc53d3671677e6a093fc74e4f9bcde57e5f7ad:858:18)
at Spec.addExpectationResult (http://localhost:9876/absolute/var/www/html/employee_portal/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?73bc53d3671677e6a093fc74e4f9bcde57e5f7ad:487:34)
at Env.fail (http://localhost:9876/absolute/var/www/html/employee_portal/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?73bc53d3671677e6a093fc74e4f9bcde57e5f7ad:1286:25)
at Function.next.fail (http://localhost:9876/absolute/var/www/html/employee_portal/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?73bc53d3671677e6a093fc74e4f9bcde57e5f7ad:4272:19)
at eval (webpack:///./node_modules/zone.js/dist/zone-testing.js?:779:30)
at eval (webpack:///./node_modules/zone.js/dist/zone-testing.js?:834:21)
at ZoneDelegate.invoke (webpack:///./node_modules/zone.js/dist/zone.js?:387:26)
at ProxyZoneSpec.onInvoke (webpack:///./node_modules/zone.js/dist/zone-testing.js?:287:39)