im working in angular 13 and im using ngRxstore. this is my code :
userState:UserState | null = null;
constructor(private store:Store<any>) {}
ngOnInit() {
// Subscribe to the user state and save info in the localstorage
this.store.subscribe((state) => {
this.userState = state.appUserState;
if(this.userState && this.userState.user){
localStorage.setItem('userState', btoa(JSON.stringify(this.userState.user.roles)) );
}
});
}
can anyone guide me how i can unit test my store subscribe in ngOninit. this is my test but it's not working:
const testStore = jasmine.createSpyObj('Store', ['subscribe']);
//....
providers: [
//..
{
provide: Store,
useValue: testStore
}
]
//...
it(`#ngOninit test'`, () => {
testStore.subscribe.and.returnValue(
of({ user: userDtoMock, errorMessage:'',dataState:UserStateEnum.LOADED })
);
fixture.detectChanges();
homeComponent.ngOnInit();
});
thanks in advance.
CodePudding user response:
Here is the general idea, adapt it to your needs :
// Mock properly
const someState = {};
const testStore = of(someState);
//....
providers: [
{
provide: Store,
useValue: testStore
}
]
//...
it(`#ngOninit test'`, (done) => { // Add a callback function for async testing
// Subscribe to your state
testStore.subscribe(state => {
// Check your test
expect(...).toXXX(...);
// Call the callback
done();
});
});