如何在角度单位测试中模拟组件中的store.pipe

问题描述 投票:0回答:1

我对angular还是陌生的,因为我试图对从存储中获取数据的组件之一进行单元测试。我嘲笑了服务文件以及商店。当我尝试运行测试时,出现如下错误。因此,我向存储中添加了一些虚假数据并通过了datas。但是仍然出现相同的问题

Cannot read property 'switches' of undefined

规格文件

describe('SwitchListComponent', () => {
  let component: ListComponent;
  let fixture: ComponentFixture<ListComponent>;

  let store: Store<any>;
  const switchData = {
    switches: [
      {
        availability: true,
        created_at: "2020-01-30T05:06:06.366Z",
        description: "1",
        hardware_id: "2",
        id: 1018,
        max_flows: 2,
        name: "2",
        updated_at: "2020-01-30T05:34:36.702Z"
      }
    ],
    pagination: {
      currentPage: 1,
      endAt: 10,
      nextPage: 2,
      perPage: 10,
      prevPage: null,
      startAt: 1,
      totalCount: 1012,
      totalPages: 100
    }
  };


  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        ListComponent,
        MultiSelectComponent,
      ],
      imports: [
        RouterTestingModule,
        FormsModule,
        StoreModule.forRoot({ switchesReducer }),
      ],
      providers: [
        {provide: SwitchesService, useClass: SwitchesServiceStub},
      ]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ListComponent);
    component = fixture.componentInstance;
    store = fixture.debugElement.injector.get(Store);
    store.dispatch({
      type: 'FETCH_SWITCHES',
      payload: {
        switches: switchData.switches,
        pagination: switchData.pagination
      }
    });
    fixture.detectChanges();
  });

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

开关列表组件

this.store.pipe(select('switches')).subscribe(val => {
  this.rowData = val.switches;
  this.pagination = val.pagination;
  this.globalSearch = val.globalSearch;
});

谁能告诉我如何对this.store.pipe进行模拟。

angular unit-testing karma-jasmine ngrx-store
1个回答
0
投票

spec.ts内部尝试将以下代码从中更改

StoreModule.forRoot({ switchesReducer }),

StoreModule.forRoot({ switches: switchesReducer }),

请参阅文档以获取更多信息

https://ngrx.io/guide/store/testing

© www.soinside.com 2019 - 2024. All rights reserved.