angular - Angular 服务测试 - 如何返回预期值?
问题描述
我试图弄清楚如何测试服务,文档引用了这个StackBlitz 示例。
在断言通过的测试中,我无法理解。当调用服务上的函数时,it('should return expected heroes (called once)'
我没有看到任何模拟或间谍设置返回,那么这是怎么回事?expectedHeroes
getHeroes()
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);
});
});
解决方案
我不知道它的实现HeroesService
是什么,但我想我可以根据测试体的其余部分做出一个很好的猜测。
当您调用 时getHeroes()
,您将获得一个可观察对象,该对象将在以后通过subscribe
处理程序实现。“较晚的日期”作为测试的最后一行出现。
httpTestingController
是(大概)跟踪由 中的事物发出的所有 HTTP 请求,TestBed
但不响应它们。当您获取请求对象(使用expectOne
)时,您就可以充当远程服务器并填充响应。
该测试是在没有修改的情况下req.flush(expectedHeroes)
正确地HeroesService
从另一侧 ( ) 冲出和冲出的测试。subscribe
推荐阅读
- php - 当 PHP “声明”一堆 HTML / PHP 标签时,这意味着什么?
- android - 自定义 View 有没有办法检测其 Activity 何时暂停或停止?
- asp.net-core - ASP.NET Core 2.2 主布局模型问题
- python - 加入列表中的许多数据在数组中不起作用 python
- html - 粘性导航显示在叠加层上方
- powershell - 在 Excel 公式中包含正斜杠
- android - 谷歌智能锁在一个应用程序中显示我所有的手机账户,而不是以前使用的那些
- python - pip install PDAL 失败,缺少 pdal-config
- windows - 从跳转返回主
- python - 如何加入两个数据框并保留每个数据框的某些列?