How do I mock selectors in nrgx 8 unit tests?

后端 未结 1 915
-上瘾入骨i
-上瘾入骨i 2021-01-21 10:28

I am learning to write unit tests for ngrx8 application using Jest.

I am testing a component that has subscription to a selector in ngOnInit:

ngOnInit():         


        
相关标签:
1条回答
  • 2021-01-21 11:22

    Mocking the selector doesn't seem to be the best solution. It would be better to mock the store itself.

    You can provide the state in :

    provideMockStore({ initialState: your_state })
    

    or

    mockStore.setState(your_state);
    

    mockStore.setState(...) allows you to do tests with different value in your store inside your tests.

    BUT I suggest you do do the following if you have a complex store:

    • create a class where you will have your mock store state: MockStoreState.
    
    type RecursivePartial<T> = {
      [P in keyof T]?:
      T[P] extends (infer U)[] ? RecursivePartial<U>[] :
        T[P] extends object ? RecursivePartial<T[P]> :
          T[P];
    };
    
    export class MockStoreState {
      private store_a: RecursivePartial<Store_A>;
      private store_b: RecursivePartial<Store_b>;
    
      build(): any {
        const defaultStore_a = {
          ...
        };
        const defaultStore_b = {
          ...
        };
    
        return {
          store_a: { ...defaultStore_a , ...this.store_a},
          store_b: { ...defaultStore_b , ...this.store_b },
        };
      }
    
      setStore_a(value: RecursivePartial<Store_A>): Store_A_State {
        this.store_a= value;
        return this;
      }
    
      setStore_b(value: RecursivePartial<DatasourceState>): Store_B_State {
        this.store_b= value;
        return this;
      }
    }
    
    • Set the state in your store in the test:
    describe(MyComponent.name, () => {
       ...
       let mockStore: MockStore<any>;
    
       beforeEach(() => {
           ...
           mockStore = TestBed.get(Store);
       })
    
    
       it('...', () => {
         const state = new MockStoreState().setStore_a({...})
        .build();
    
        mockStore.setState(state);
    
       // HERE you have set the data in your store.
       })
    }
    
    0 讨论(0)
提交回复
热议问题