Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

it('should call getUsersById', () => {
  const user: User [] = [
    {
      "id": 23556,
      "name": "unique Ramakrishna",
      "email": "new.ramakrishna@15ce.com",
      "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?

>Solution :

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": "new.ramakrishna@15ce.com",
      "gender": "male",
      "status": "active"
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading