【发布时间】:2019-01-09 19:03:19
【问题描述】:
我正在尝试弄清楚如何测试服务,docs 引用了这个StackBlitz example。
我无法理解 如何,在断言通过的it('should return expected heroes (called once)' 测试中。当调用服务上的 getHeroes() 函数时,我没有看到任何模拟或间谍设置返回 expectedHeroes,那么这是怎么回事?
describe('#getHeroes', () => {
let expectedHeroes: Hero[];
beforeEach(() => {
heroService = TestBed.get(HeroesService);
expectedHeroes = [
{ id: 1, name: 'A' },
{ id: 2, name: 'B' },
] as Hero[];
});
it('should return expected heroes (called once)', () => {
//------------------------------------------
// HOW IS THIS PASSING???
heroService.getHeroes().subscribe(
heroes => expect(heroes).toEqual(expectedHeroes, 'should return expected heroes'),
fail
);
// HeroService should have made one request to GET heroes from expected URL
const req = httpTestingController.expectOne(heroService.heroesUrl);
expect(req.request.method).toEqual('GET');
// Respond with the mock heroes
req.flush(expectedHeroes);
});
});
【问题讨论】:
-
在进行 http 调用之前,
req.flush(expectedHeroes)似乎使用httpTestingController从 Angular 中更深层次的东西返回expectedHeroes。所以直接嘲讽的不是getHeroes。然后.subscribe运行,expect通过。
标签: angular unit-testing