【问题标题】:ngrx component unit test : how to set store value and make the subscribe callngrx 组件单元测试:如何设置存储值并进行订阅调用
【发布时间】:2019-08-18 03:50:51
【问题描述】:

我正在为我的组件编写单元测试。我想测试/覆盖我在订阅中调用函数 calculateJohnDoe 的部分。请参考以下内容:

ngOnInit(): void {
    this.authStore$ = this.store.select('auth');
    this.authStore$.subscribe(authData => {
      if (authData && authData.myprop) {
          this.calculateJohnDoe();
        }
    });
}

我在规范中尝试做的事情如下:

describe(..., () => {
  let mockStore: MockStore<AuthState>;

    // Testbed configuration
      providers: [ Store ]
      }).compileComponents();

      mockStore = TestBed.get(Store);
    ...

    it('should call the function', () => {
        mockStore.setState({
           myprop: true
        });
        const spy = jest.spyOn(LoginComponent.prototype, 'calculateJohnDoe');
        expect(spy).toHaveBeenCalled();
    });

    ...

});

但问题是我从未在调用的组件 ts 文件中获得 myprop 真正更新的存储事件/callack。

【问题讨论】:

    标签: angular unit-testing jestjs ngrx


    【解决方案1】:

    您可以创建一个代表您的商店的模拟服务,该类将模拟一个具有属性_anObservable 的可观察主题:

    class MockService {
        _anObservable = new Subject();
        select(prop: string) {
            return this._anObservable.asObservable();
        }
    }
    
    describe(..., () => {
    
        // Testbed configuration
        providers: [
            { provide: YourStore, useClass: MockService }
        ]
    
        ...
    
        it('should call the function', inject([YourStore], (store) => {
            const spy = jest.spyOn(LoginComponent.prototype, 'calculateJohnDoe');
            store._anObservable.next({
                myprop: true
            });
            expect(spy).toHaveBeenCalled();
        }));
    
        ...
    
    });
    

    【讨论】:

    • 我收到以下错误。我还编辑了主线程,说明我如何使用 mockStore。 at getInjectableDef (node_modules/@angular/core/bundles/npm_package.esm5/packages/core/packages/core/src/di/defs.ts:171:15)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 2021-04-12
    相关资源
    最近更新 更多