Angular 13在ngOninit中模拟ngrx Store订阅



我在angular 13中使用ngRxstore。这是我的代码:

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

});

}

谁能指导我如何在ngOninit中单元测试我的商店订阅。这是我的测试,但它不工作:

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.

大致思路如下,根据您的需要调整:


// 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();
});
});

最新更新