med*_*d.b 3 unit-testing jasmine rxjs typescript angular
我正在按照这个例子对服务进行单元测试(来自spring app后端的get请求)https://angular.io/guide/testing#testing-http-services
服务类:
@Injectable()
export class TarifService {
constructor(private messageService: MessageService, private http: HttpClient) { }
public getTarifs(): Observable<Tarif[]> {
return this.http.get<Tarif[]>(tarifffsURL).pipe(
tap(() => {}),
catchError(this.handleError('getTarifs', []))
);
}
}
Run Code Online (Sandbox Code Playgroud)
单元测试
describe('TarifService', () => {
let tarifService: TarifService;
let httpClientSpy: { get: jasmine.Spy };
let expectedTarifs;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ToastrModule.forRoot(), HttpClientModule, HttpClientTestingModule],
providers: [TarifService, HttpClient, MessageService]
});
httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']);
tarifService = new TarifService(<any> MessageService,<any> httpClientSpy);
});
it('should be created', inject([TarifService], (service: TarifService) => {
expect(service).toBeTruthy();
}));
it('should return expected tarif (HttpClient called once)', () => {
const expectedTarifs: Tarif[] =
[{ id: 1, name: 'Tarif1', value: '20' }, { id: 2, name: 'Tarif2', value:'30' }];
httpClientSpy.get.and.returnValue(expectedTarifs);
tarifService.getTarifs().subscribe(
tarifs => expect(tarifs).toEqual(expectedTarifs, 'expected tarifs'),
fail
);
expect(httpClientSpy.get.calls.count()).toBe(1, 'one call');
});
});
Run Code Online (Sandbox Code Playgroud)
运行测试时,我一直有这个错误
TarifService should return expected tarif (HttpClient called once)
TypeError: this.http.get(...).pipe is not a function
Run Code Online (Sandbox Code Playgroud)
这可能是什么原因?
Cas*_*Roy 10
问题是当你spy被调用时,它返回一个Array并且Array没有pipe函数.你需要Observable从你spy这样的东西中 返回一个
const expectedTarifs: Tarif[] =
[{ id: 1, name: 'Tarif1', value: '20' }, { id: 2, name: 'Tarif2', value:'30' }];
httpClientSpy.get.and.returnValue(Observable.of(expectedTarifs));
Run Code Online (Sandbox Code Playgroud)
看怎么returnValue是Observable.of(expectedTarifs).Observable.of创建一个Observable发出一些您指定为参数的值,一个接一个地发出,然后发出完整的通知.查看文档
希望能帮助到你
| 归档时间: |
|
| 查看次数: |
7859 次 |
| 最近记录: |