I am looking to test the get and set methods of my user.store.ts file. The get() method is used to retrieve users, while addUsers() is utilized to add new Users to the BehaviorSubject. How can I accomplish this?
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 expect that values will be added when addUsers() is called, and I can retrieve users by calling get users(). I am relatively new to Angular Testing.
An error message similar to the following has been appearing:
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' }) ].
The structure of my User[] object is as follows:
{
'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);
});
}));
});`