Angular Karma Jasmine Unit Test An error was thrown in afterAll TypeError: users.forEach is not a function

Angular Karma Jasmine Unit Test An error was thrown in afterAll TypeError: users.forEach is not a function

我是下面代码的单元测试用例。我提到了组件和 component.ts.spec 文件。

组件代码。

  this.commonService.postdata('users', request).subscribe((users: any[]) => {
          users.forEach((data) => {
               this.usersList.push({ name: data['firstName'] + ' ' + data['lastName'], id: 
               data['id'] });
           }
   } });

我在使用时遇到问题,请参阅下面的代码 spec.ts 文件

Spec.ts 文件代码

       class MockCommonService {
          postdata() {
            return of();
          }
        }
describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyViewComponent>;
  let commonService: CommonService;
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [HttpClientTestingModule, RouterTestingModule, HttpClientModule],
      declarations: [MyComponent],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      providers: [ { provide: CommonService, useValue: new MockCommonService() }]
    })
      .compileComponents();
  });
  beforeEach(() => {
    fixture = TestBed.createComponent(MyViewComponent);
    commonService = TestBed.inject(CommonService);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
}
          it('list', () => {
            const x = spyOn(component, 'list').and.callThrough();
        
        const req = {
              "groupnm": ['21'],
              "grouptp": "ABC",
         };
            spyOn(commonService, 'postdata').and.returnValue(of(req));
        component.list();
            expect(x).toHaveBeenCalled();
        });
    
 

  

我已经写了上面的代码但遇到了问题。在 Angular 单元测试用例中非常新,所以请建议正确的代码。我在这里做错了什么?

提前致谢。

users.forEach 不是函数,因为 users 不是数组。在您的测试中,const req 是一个对象而不是数组,但在组件代码中 postdata 返回 observable< array >.

在测试中应该是const req = [some array]