家伙!我是测试人员的新手,并且一直坚持这个问题。我正在尝试为我的服务编写单元测试,该测试从服务器获取数据。古典案例:
import {TestBed} from '@angular/core/testing';
import {ShiftsService} from "./shifts.service";
import {Shift} from "../shift/shift";
describe('ShiftService - testing HTTP request method getShifts()', () => {
let httpTestingController: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [ShiftsService]
});
});
it('can test HttpClient.get', () => {
let shifts = new Array<Shift>();
let shiftsService;
let calendarMonth = new Date().getMonth()+2;
let calendarYear = new Date().getFullYear();
shiftsService = TestBed.inject(ShiftsService);
httpTestingController = TestBed.inject(HttpTestingController);
shiftsService.getShifts(calendarYear, calendarMonth).subscribe(response => {expect(response).toBe(response.length);
console.log(response);
});
let apiRequest:string = '/api/shifts?year='.concat(calendarYear.toString()).concat('&month=').concat(calendarMonth.toString());
const req = httpTestingController.expectOne(apiRequest);
console.log(apiRequest);
expect(req.request.method).toBe('GET');
req.flush(shifts);
});
afterEach(() => httpTestingController.verify());
});
我的服务文件中的方法如下:
getShifts (year: number, month: number): Observable<Shift[]> {
let params = new HttpParams();
params = params.append('year', year.toString());
params = params.append('month', month.toString());
return this.http.get<Shift[]>(this.shiftsUrl, { params: params })
.pipe(tap((shifts) => shifts),
catchError((err) => this.handleError(err)))
}
我收到错误:错误:期望[]为0。当我打印出response变量时,我发现它为空!但我敢肯定,这种方法可以正常工作!在我的应用程序中效果很好!您能帮我解决这个问题吗?如何更正我的测试方法以测试服务?
it('can test HttpClient.get', (done) => { // add done callback to be able to call it in the subscribe
let shifts = new Array<Shift>();
let shiftsService;
let calendarMonth = new Date().getMonth()+2;
let calendarYear = new Date().getFullYear();
shiftsService = TestBed.inject(ShiftsService);
httpTestingController = TestBed.inject(HttpTestingController);
shiftsService.getShifts(calendarYear, calendarMonth).subscribe(response => {
// we have to use toEqual because toBe does a deep assertion
// but the array to compare to is in a different location in memory so
// toBe would fail
expect(response).toEqual([]);
console.log(response);
// call done to tell the unit test you are done with this test
done();
});
let apiRequest:string = '/api/shifts?year='.concat(calendarYear.toString()).concat('&month=').concat(calendarMonth.toString());
const req = httpTestingController.expectOne(apiRequest);
console.log(apiRequest);
expect(req.request.method).toBe('GET');
req.flush(shifts);
});