【问题标题】:Solve "An error was thrown in afterAll with is not iterable" in Angular test with Karma/Jasmine在使用 Karma/Jasmine 的 Angular 测试中解决“在 afterAll 中抛出一个错误,不可迭代”
【发布时间】: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


    【解决方案1】:

    这是我第一次看到resetTestingModule,我不确定它是否需要。

    我觉得你的回答有点不对劲。

    试试这个:

      it('should be have a call /my-url', () => {
        const mockResponse: RealDataModel = {
          // !! change books to data here !!
          data: [{...}] 
        };
    
        service.getData().subscribe(data => {
          expect(data).toEqual(mockResponse);
        });
    
        const testReq = httpTestingController.expectOne('/my-url');
    
        expect(testReq.request.method).toEqual('GET');
        testReq.flush(mockResponse);
      });
    

    【讨论】:

      猜你喜欢
      • 2019-12-23
      • 2021-09-06
      • 2019-05-05
      • 1970-01-01
      • 2021-12-27
      • 2018-10-31
      • 2019-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多