Search code examples
angularangular-test

Getting Error NG02200 while testing my Angular component


I am creating a dummy project for my learning, and hence reading data from session storage. I have to write test case for the following file:

TS File

export class DashboardComponent implements OnInit {
existingUsers: User[] = [];

constructor(
private userservice: UserserviceService,
private routerService: Router
 ) {}
 ngOnInit(): void {
 this.existingUsers = JSON.parse(
   sessionStorage.getItem('usersData') || '{}'
  );

this.userservice.newUserSubject.subscribe((user:any[]) => {
  if (user.length >= 1) {
    this.existingUsers.push(user[user.length - 1]);
  }
});

sessionStorage.setItem('usersData', JSON.stringify(this.existingUsers));
}
}

HTML file

 <div class="container responsive-grid">
  <mat-card *ngFor="let users of existingUsers; let index = index">
    <mat-card-header>
  <mat-card-title>{{ users.name }}</mat-card-title>
</mat-card-header>
<mat-card-actions>
  <button (click)="editUser(index, users)">Edit User</button>
  <button (click)="deleteUser(index)">Delete User</button>
</mat-card-actions>
<br />
<mat-card-content>
  <br />
  <div>
    <strong><label for="name">Name</label></strong> {{ users.username
    }}<br />
    <strong><label for="username">Email</label></strong> {{ users.email
    }}<br />
    <div>
      <strong> Address</strong>
      <div>
        <strong><label for="street">Street</label></strong>
        {{ users.address.street }}<br />
      </div>
      <div>
        <strong><label for="suite">Suite</label></strong>
        {{ users.address.suite }}<br />
      </div>
      <div>
        <strong
          ><label for="city">City</label> {{ users.address.city }}</strong
        ><br />
      </div>
      <div>
        <strong><label for="zipcode">PinCode</label> </strong
        >{{ users.address.zipcode }}<br />
      </div>
    </div>
  </div>
</mat-card-content>

Spec.ts File for unit testing

  it('should create', () => {
  expect(component).toBeTruthy();
  });

this default test case if failing for the above code

Error Message

Error: NG02200: Cannot find a differ supporting object '[object Object]' of type 'object'.
         NgFor only supports binding to Iterables, such as Arrays.
         Did you mean to use the keyvalue pipe?

I have tried to create a existingUser Array in Spec file


Solution

  • The problem is that in your ngOnInit() you are setting this.existingUsers to an empty object in case the session storage does not return any matching item. However, *ngFor expects an array. This is relevant for your test case, as the testing environment has an empty session storage by default. To fix it, just use empty array instead of empty object.

    this.existingUsers = JSON.parse(
      sessionStorage.getItem('usersData') || '[]'
    );
    

    To have better type safety, you can also refactor the code a bit:

    const storedUsers = sessionStorage.getItem('usersData');
    this.existingUsers = storedUsers ? JSON.parse(storedUsers) : [];
    

    Now TypeScript will warn you if you use {} instead of [].