menu

Questions & Answers

Angular | How to write unit test for add element method?

I'm trying to create a test for the add method to add a new user, but Jasmine doesn't count the new item I add.

The result that appears is: Expected 3 to be 4.

Below is my code:

  beforeEach( () => {
    USERS = [
      {
      "id": 34795,
      "name": "User",
      "email": "sadasGuru@email.com",
      "gender": "male",
      "status": "active"
      },
      {
      "id": 34791,
      "name": "emailc",
      "email": "sdadsada@gmail.com",
      "gender": "male",
      "status": "active"
      },
      {
      "id": 34790,
      "name": "ssasdasa",
      "email": "emailproava@mai.com",
      "gender": "male",
      "status": "active"
      }]   
    //Mock UserComponent
    mockPostService = jasmine.createSpyObj(['delete', 'add'])
    component = new UserComponent(mockPostService)

  it('should ADD User from users', ()=>{
    mockPostService.add.and.returnValue(of(true));
    mockComponent.users = USERS
    mockComponent.add('Rachida','female','email23@rachida.com','active')
    expect(mockComponent.users.length).toBe(4) // RESULT: Expected 3 to be 4.
  })
  });

user.component.ts

  add(name: string, gender: string, email: string, status: string): void {
    name = name.trim();
    gender = gender.trim();
    email = email.trim();
    status = status.trim();
    this.userService.APIkey = this.urlVal as string
      this.userService.addUser(email, name, gender, status).subscribe((data) => {
        this. getUsers()
        },
      (error)=>{
        if (error.status) {
          alert('Errore: ' + JSON.stringify(error.error));
        }
   });

Where am I doing wrong?

Comments:
2023-01-07 20:31:11
There are only 3 users in the array you're using to test. I suggest you replace the number 4 in your assertion with USERS.length.
2023-01-07 20:31:11
@WillAlexander I tried that but I always get the same result.
Answers(0) :