Angular 13 在 ngOninit 中模拟 ngrx 商店订阅

Angular 13 Mock ngrx Store Subscribe in ngOninit

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

提前致谢。

这里是大致的思路,根据您的需要进行调整:


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