我正在尝试对HTTP异步服务进行单元测试。
我的服务:
@Injectable()
export class MenuService {
url = 'http://localhost:8080/rest/menu';
constructor(private httpClient: HttpClient) {
}
async getMenus() {
return this.httpClient.get<MenuData[]>(this.url).toPromise();
}
}
我的测试
describe('MenuService', () => {
let service: MenuService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [MenuService],
});
service = TestBed.get(MenuService);
httpMock = TestBed.get(HttpTestingController);
});
it('should get all menus', async () => {
const menus = service.getMenus().then((data: MenuData[]) => {
expect(data.length).toBe(2);
});
const req = httpMock.expectOne('http://localhost:8080/rest/menu', 'call to api');
expect(req.request.method).toEqual('GET');
req.flush([<MenuData>{id: 1, name: 'Test', discreteSubMenus: false, subMenus: false}]);
});
afterEach(() => {
httpMock.verify();
});
});
测试结果如下
如果我将async getMenus()
更改为
getMenus(): Observable<MenuData[]> {
return this.httpClient.get<MenuData[]>(this.url);
}
哪个看起来更正确。因为MenuService测试失败,而不是整个测试失败。如何更改测试代码以正确测试异步方法?
答案 0 :(得分:0)
如果有选择,我将始终选择Observables
来为后端编写服务。
您可以将Service
方法更改为
getMenus(): Observable<MenuData[]> {
return this.httpClient.get<MenuData[]>(this.url);
}
您的测试方法更改为
it('should get all menus', async () => {
//Prepare Mock Menu Data
let mockMenu = [<MenuData>{id: 1, name: 'Test', discreteSubMenus: false, subMenus: false}];
const menus = service.getMenus().subscribe((data: MenuData[]) => {
expect(data.length).toBe(2);
// Other asserts about the received response here
});
// Asserts of the api call here
const req = httpMock.expectOne('http://localhost:8080/rest/menu', 'call to api');
expect(req.request.method).toEqual('GET');
req.flush(mockMenu);
});