简体   繁体   中英

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 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)
  })
}))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM