我正在尝试了解如何创建htpClientSpy,根据测试服务的Angular文档。目前我有这个设置:
import { TestBed } from '@angular/core/testing';
import { AuthService } from '../../../core/auth/auth.service';
import { PermissionsService } from '../services/permissions.api.service';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { Observable } from 'rxjs/Observable';
import { map } from 'rxjs/operators';
describe('PermissionsService', () => {
let permissionsService: PermissionsService;
let httpClientSpy: { get: jasmine.Spy };
let authClientSpy: { get: jasmine.Spy };
beforeEach(() => {
httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']);
authClientSpy = jasmine.createSpyObj('Http', ['get']);
permissionsService = new PermissionsService(new AuthService( <any> authClientSpy), <any> httpClientSpy);
});
it('should refresh global permissions using refreshGlobalPermissions', () => {
const mockGlobalResponse = { global_actions: ['permission1', 'permission2', 'permission3']};
httpClientSpy.get.and.returnValue(mockGlobalResponse);
permissionsService.refreshGlobalPermissions().subscribe(
permissions => expect(permissions).toEqual(mockGlobalResponse, 'expected global permissions'),
fail
);
expect(httpClientSpy.get.calls.count()).toBe(1, 'one call');
});
}
但是,当我从控制台运行ng test
时(这是我唯一的测试),我收到此错误:
TypeError:this.httpClient.get(...)。map不是函数
根据我的发现,我需要做的就是在我的* .spec.ts文件中导入map
,但这似乎不起作用。我在这里缺少什么吗?
编辑: 服务我正在测试:
public refreshGlobalPermissions(): any {
const globalPermissions = this.globalPermissions;
if (globalPermissions.length === 0) {
const url = `${this.baseUrl}?permissions`;
return this.httpClient.get(url).map((response) => {
this.globalPermissions = response['global_actions'];
});
}
return Observable.of(true);
}
答案 0 :(得分:1)
HttpClient.get()
返回一个Observable。您的生产代码在此Observable上调用map()
。
但是在你的代码中,你的get()方法的间谍不会返回一个Observable。它返回mockGlobalResponse
,这是一个POJO。所以这不可行。
我建议你不要以这种方式监视HttpClient,而是使用专用于HttpClient的测试支持,described in the documentation。