angular - Angular 8 Jasmine 不匹配 HTTP 请求
问题描述
我有一个 Angular 服务发出一些 HTTP 请求,我想测试它是否使它们以正确的方式。
在它的依赖项中,它还有一个EnvironmentService
根据环境返回正确的 API 端点,我用 Jasmine 模拟过。
我的测试如下所示:
describe('ShipmentsService', () => {
let httpTestingController: HttpTestingController;
let service: ShipmentsService;
const envSpy = jasmine.createSpyObj('EnvironmentService', ['getRestEndpoint', 'dev']);
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
ShipmentsService,
{provide: EnvironmentService, useValue: envSpy}
],
imports: [HttpClientTestingModule]
});
httpTestingController = TestBed.get(HttpTestingController);
service = TestBed.get(ShipmentsService);
});
it('does the right HTTP request', () => {
envSpy.getRestEndpoint.and.returnValue('foo');
service.doStuff(123);
expect(envSpy.getRestEndpoint)
.toHaveBeenCalledWith('changePackingProperties');
const request = httpTestingController.expectOne('foo');
request.flush({shipmentId: 123});
httpTestingController.verify();
});
});
这是我的ShipmentsService
方法:
doStuff(shipmentId: number) {
let path = this.environmentService.getRestEndpoint('changePackingProperties');
return this.http.post(path, body, {headers}).pipe(map(
(response) => response
));
}
我错过了什么?
解决方案
缺少的是我的服务方法确实返回了一个Observable
,所以要完成它,需要对它进行测试subscribe
。
那么,为了使测试工作,实际的服务调用需要
service.doStuff(123).subscribe(() => {});
推荐阅读
- r - 在 FlexDashboard 中过滤。过滤选项不是数据集的一部分
- reactjs - 当回调在父级中更改状态时,如何使用 React.memo 和 useCallback 优化 React 组件
- git - Git 在上一个差异之后添加
- angular - 角度测试因 takeWhile() 而失败
- laravel - 我从远程服务器上读到了一些难看的字母
- c# - 在 Unity Vuforia 插件中捕获 VideoBackground 的快照
- c# - LINQ to SQL:插入子实体失败,因为 SQL 中不包含 ID?
- c# - 实体框架不刷新数据
- java - 使用 ReadOnlyPDOMProvider 导入索引内容
- c - C标准中可变修改类型的switch语句约束说明