Home > Enterprise >  Angular Karma Jasmine Unit Test An error was thrown in afterAll TypeError: users.forEach is not a fu
Angular Karma Jasmine Unit Test An error was thrown in afterAll TypeError: users.forEach is not a fu

Time:11-17

I am unit test case for below code. I have mention component and component.ts.spec file.

Component Code.

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

I am facing issue while users and please see below code spec.ts file

Spec.ts File Code

       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();
        });
    
 

  

I have written above code but facing issue. Very new in Angular unit test case so please suggest correct code. What I am doing wrong here?

Thanks in Advance.

CodePudding user response:

users.forEach is not a function because users is not an array. In your test, const req is an object not an array, but in component code postdata is returning observable< array >.

In test it should be const req = [some array]

  • Related