Home > Enterprise >  Angular | The argument of type 'User[]' cannot be assigned to the parameter of type '
Angular | The argument of type 'User[]' cannot be assigned to the parameter of type '

Time:01-07

During angular testing I get this error, I can't figure out where it comes from in any way.

The error is related to the user inside toBe()

user.service.spec.ts

it('should call getUsersById', () => {
  const user: User [] = [
    {
      "id": 23556,
      "name": "unique Ramakrishna",
      "email": "[email protected]",
      "gender": "male",
      "status": "active"
    }
  ]

  userService.APIkey = '89668b2e3000a3aab5860410aa59fdc6c98977afa03a15d19df6be0e22f91650'
  let APIkey = userService.APIkey
  let url = 'https://gorest.co.in/public/v2/users'
  let nUsers = '10';
  let nPage = 1;
  let id = 23556
  userService.getUserById(id).subscribe((res) => {
   expect(res).toBe(user) // ERROR:The argument of type 'User[]' cannot be assigned to the parameter of type 'Expected<User>'.
  });

  const req = httpTestingController.expectOne({

    method: 'GET',
    url: `${url}/${id}?access-token=${APIkey}`,
  });

  req.flush(user);
});

user.service.ts This is the GET by ID call I make from the service

  /** GET user by id(DETAIL) */
  getUserById(id: number): Observable<User> {
    const url = `${this.url}/${id}?access-token=${this.APIkey}`;
    return this.http.get<User>(url).pipe(
      tap(_ => this.log(`fetched user id=${id}`)),
      catchError(this.handleError<User>(`getUser id=${id}`))
    );
  }

User.ts

export interface User {
  id: number;
  name: string;
  email: string;
  gender: string;
  status: string;
}

I searched online but didn't find any solution. Can anyone help me?

CodePudding user response:

You get this error because in your code res is a User and user is an array of User. You can either take the first element of your array: expect(res).toBe(user[0]) or (probably more appropriate) refactor your code so that user is an object not an array:

const user: User = {
      "id": 23556,
      "name": "unique Ramakrishna",
      "email": "[email protected]",
      "gender": "male",
      "status": "active"
    }
  • Related