首页 > 解决方案 > 无法读取未定义的“管道”

问题描述

我正在尝试对角度组件进行单元测试。我是单元测试的新手,我目前面临以下问题

我的组件有如下选择语句:

this.store.select(getInfo)
    .pipe(takeWhile(() => this.isLive)
    )
    .subscribe((data) => {
      this.text = data;

    }); 

我的单元测试用例是这样写的:

fdescribe(‘TestComponent', () => {
  let component: TestComponent;
  let fixture: ComponentFixture<TestComponent>; 

  const testStore = jasmine.createSpyObj('Store', ['select']);

  beforeEach(async(() => {

    TestBed.configureTestingModule({
      declarations: [TestComponent
        ],
      imports: [MaterialModule, FiltersModule],
      providers: [
        {provide: Store, useValue: testStore }],

      schemas: [NO_ERRORS_SCHEMA]
    })

      .compileComponents();
  }));

  beforeEach(() => {


    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

  });

  it('should create Test component', async() => {
    let initialState = {
         data: {
    “name: “xyz”,
    “age” : 20

    } , 
      info: [1]
    };

    testStore.select.and.returnValues(

       of(initialState.info)
     );
     fixture.detectChanges();
     await fixture.whenStable();
    expect(component).toBeTruthy();
  });
  it('should have at least 1 info’, async() => {
    let initialState = {
         data: {
    “name: “xyz”,
    “age” : 20

    } , 
      info: [1]
    };

    testStore.select.and.returnValues(

       of(initialState.info)
     );

    fixture.detectChanges();
    await fixture.whenStable();

    console.log("text is ",component.text);
    });

});

这是一个非常幼稚的测试。在继续编写更复杂的测试之前,我只是想了解基本概念。所以,我面临的问题是。它提示我一个错误说: TypeError: Cannot read property 'pipe' of undefined 并且这只发生在 ''should create Test component' testcase 。其他测试用例按预期登录消息。

我无法理解我哪里出错了。

标签: angulartypescriptkarma-jasmine

解决方案


当您提供服务时,每个测试都会获得所提供对象的单独副本。您正在将 testStore.select 的值设置为测试本身内部的原始对象。你有两个选择。第一个是testStore.select在你在 beforeEach 中声明 Jasmine 间谍之后立即设置。第二个选项是在测试中获取对 testStore 的引用并分配给它。

const service = TestBed.get(Store) as Store;
service.select = jasmine.createSpy('select').and.returnValue(of(info));

您选择哪个选项取决于您。由于我没有看到对组件方法的调用,因此我假设您显示的组件代码是从 onInit 调用的。在这种情况下,第一个选项更易于使用。

如果您想更改info每个测试的外观,您可以使用选项二,或者component.onInit()在设置选择方法将返回的内容后调用,或者在设置选择fixture.detectChanges后延迟第一个。这意味着fixture.detectChanges从你的 beforeEach 中删除。

您很可能不需要异步或whenStable为此工作。


推荐阅读