【发布时间】:2021-08-10 12:42:03
【问题描述】:
我在运行 Karma 的 Angular 测试时遇到此错误:
An error was thrown in afterAll
TypeError: data.data is not iterable
这是我要测试的服务:
getData(): Observable<RealDataModel> {
return this.http.get<DataResponseModel>('my-url')
.pipe(
map((data: DataResponseModel) => (
{ books: [...data.data] }
))
);
}
我的 get 返回一个类似的对象(DataResponseModel):
{
data: [{...}]
}
但我需要将它映射到这样的对象中
export class RealDataModel {
books: [{...}];
// Other info that I put using .map
}
这是我的测试,我在谷歌搜索后添加了 verify 和 resetTestingModule 希望解决问题,但它似乎不起作用:
describe('DataService', () => {
let service: DataService;
let httpTestingController: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule
]
});
service = TestBed.inject(DataService);
httpTestingController = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpTestingController.verify();
});
afterAll(() => {
TestBed.resetTestingModule();
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should be have a call /my-url', () => {
const mockResponse: RealDataModel = {
books: [{...}]
};
service.getData().subscribe(data => {
expect(data).toEqual(mockResponse);
});
const testReq = httpTestingController.expectOne('/my-url');
expect(testReq.request.method).toEqual('GET');
testReq.flush(mockResponse);
});
});
【问题讨论】:
标签: angular typescript unit-testing jasmine karma-jasmine