Angular Ngrx商店测试`状态名称“ storeOne”在该状态中不存在”

时间:2019-10-02 09:30:37

标签: angular8 ngrx-store angular-test ngrx-store-8.0

通过以下视频进行ngrx隔离测试后: John Crowson - Using MockStore in NgRx 8 | AngularUP

我试图通过我的简单项目实现相同的目标。但是我遇到了我无法理解的错误。有人帮我解决吗?

对我来说是很大的帮助。

测试ts文件:

euclidean distances

运行后,出现以下错误:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { provideMockStore, MockStore } from '@ngrx/store/testing';
import { ShellHomeComponent } from './shell-home.component';
import { StoreOne } from './../../models';
import { Store, select } from '@ngrx/store';
import { cold } from 'jasmine-marbles';

describe('ShellHomeComponent', () => {

    let component: ShellHomeComponent;
    let fixture: ComponentFixture<ShellHomeComponent>;
    let mockStore: MockStore<StoreOne>;

    const loadingState = {
        loading: true,
        items: [{ name: '1' }]
    } as StoreOne;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [ ShellHomeComponent ],
            imports: [],
            providers: [provideMockStore({initialState: loadingState})]
        })
        .compileComponents();

        mockStore = TestBed.get(Store);

    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(ShellHomeComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });

    it('should display loading as true', () => {
        const expected = cold('loading', { loading: false, items: [{ name: '3' }] });
        expect(component.loading).toBeObservable(expected);
    });

});

2 个答案:

答案 0 :(得分:2)

要建立Danny的答案,您将执行以下操作:

      providers: [
        provideMockStore({
          initialState: {
            'addInvestigationModal': initialState
          }
        })
      ]

但是,我仍然遇到错误An error was thrown in afterAll error properties: Object({ longStack: 'TypeError: Cannot read property 'property_name' of undefined

我通过添加

来解决此问题
afterEach(() => {
    fixture.destroy();
  });

答案 1 :(得分:0)

我有类似的问题。我的测试失败了,因为在我的reducer中的state是未定义的。我还在控制台中收到一条警告,提示The feature name "my-feature" does not exist in the state's root, therefore createFeatureSelector cannot access it. Be sure it is imported in a loaded module using StoreModule.forRoot('my-feature', ...) or StoreModule.forFeature('my-feature', ...).

问题是当我需要为整个应用提供模拟存储时,我为功能提供了模拟存储。

尝试将provideMockStore({initialState: loadingState})更改为类似provideMockStore<State>({initialState: {shellComponent: loadingState}})的名称,其中State是应用程序的全局状态的名称(确保从应用程序的{{1}导入State }文件,而不是state.ts),而@ngrx/store是您要测试的功能的名称。