Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test Behaviour Subjects in Angular

I want to test get and set method of my user.store.ts. I have a get() which is used to get users and addUsers() which is used to add Users into the BehaviourSubject. How Can I achieve that?

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { User } from 'ngx-login-client';

@Injectable({
  providedIn: 'root'
})

export class UserStore {

  private _users: BehaviorSubject<User[]> = new BehaviorSubject([]);

  get users() {
    return this._users.asObservable();
  }

  addUsers(users: User[]) {
    this._users.next(users);
  }
}

I expected the output to be values getting added when addUsers() is called and can get users when I call get users().I'm new to Angular Testing.

Getting an error something like:

Expected Observable({ _isScalar: false, source: BehaviorSubject({ _isScalar: false, observers: [ ], closed: false, isStopped: false, hasError: false, thrownError: null, _value: [ Object({ attributes: Object({ fullName: 'name', imageURL: '', username: 'myUser' }), id: 'userId', type: 'userType' }) ] }) }) to equal [ Object({ attributes: Object({ fullName: 'name', imageURL: '', username: 'myUser' }), id: 'userId', type: 'userType' }) ].

My User[] is of type:

{
    'attributes': {
        'fullName': 'name',
        'imageURL': '',
        'username': 'myUser'. 
    },
    'id': 'userId',
    'type': 'userType'
}

update: My user.store.spec.ts file.

import { TestBed, async } from '@angular/core/testing';

import { UserStore } from './user.store';
import { BehaviorSubject } from 'rxjs';
import { User } from 'ngx-login-client';

describe('UsersStore', () => {
  beforeEach(() => TestBed.configureTestingModule({}));

  it('should be created', () => {
     const store: UserStore = TestBed.get(UserStore);
     expect(store).toBeTruthy();
  });
  it('should add Users', async(() => {
    let store: UserStore;
    store = TestBed.get(UserStore);
    let user: User[];
    const testUser: User[] = [{
      'attributes': {
      'fullName': 'name',
      'imageURL': '',
      'username': 'myUser'
    },
    'id': 'userId', 
    'type': 'userType'
   }];
   store.addUsers(testUser);
   store.users.subscribe(users => {
     expect(users).toBe(testUser);
     });
  }));
});`
like image 921
Rajat Singh Avatar asked Dec 26 '18 06:12

Rajat Singh


Video Answer


1 Answers

Like error said, given data is Observable but your test case is Object.

You have to write like this:

it('should get users', async(() => {
  component.users.subscribe(users => {
    fixture.detectChanges()
    expect(users).toBe(testUsers)
  })
}))
like image 159
zmag Avatar answered Oct 19 '22 20:10

zmag