茉莉花->设置组件时无法读取未定义的属性订阅

时间:2019-09-09 07:36:25

标签: angular unit-testing rxjs jasmine ngrx-store

我在ngOnInit中有简单的管道。在创建组件时,如标题中所述引发错误。 TypeError:无法读取未定义的属性“ subscribe”     在ShoppingCartListComponent.ngOnInit(http://localhost:9876/_karma_webpack_/webpack:/src/app/customer-dashboard/user/shopping-cart-list/shopping-cart-list.component.ts:34:6

第34行是管道上的.subscribe()。

代码如下:

组件:

export class ShoppingCartListComponent implements OnInit {
  dataSource;
  columnsToDisplay = ['title', 'location', 'date'];
  expandedElement: Event | null;

  constructor(private store: Store<AppState>) { }

  ngOnInit() {
    this.store.pipe(
      select(selectEventsFromShoppingList),
      tap(events => this.dataSource = events),
    ).subscribe();
  }

}

测试:

fdescribe('ShoppingCartListComponent', () => {
  let component: ShoppingCartListComponent;
  let fixture: ComponentFixture<ShoppingCartListComponent>;
  let storeSpy;

  beforeEach(async(() => {
    storeSpy = jasmine.createSpyObj('Store', ["select","pipe"]);

    TestBed.configureTestingModule({
      declarations: [ ShoppingCartListComponent ],
      imports: [
        MaterialModule,
        RouterTestingModule
      ], 
      providers: [
        { provide: Store, useValue: storeSpy }
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {

    fixture = TestBed.createComponent(ShoppingCartListComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

我在这里想念什么?我应该提供一些默认状态吗?或者也许尝试使用spOn()。and.returnValue?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

此代码的问题是storeSpy是一个包含一堆未初始化间谍的对象。您还需要向pipe添加一个返回值。您可以执行以下操作:

subscribe.pipe.and.returnValue(jasmine.createSpy())

还有其他选择,但这是最简单的。