茉莉花测试用例无法读取未定义的属性“关闭”

时间:2018-09-07 05:36:47

标签: angular typescript jasmine karma-jasmine

我试图为close方法编写单元测试用例,但是当我做ng test时遇到以下错误

TypeError: Cannot read property 'close' of undefined

下面是我的测试代码

describe('CPComponent', () => {
    let fixture: ComponentFixture<CPComponent>;
    let component: CPComponent;
    let de: DebugElement;
    let el: HTMLElement;


    beforeEach(() => {
        TestBed.configureTestingModule({
            schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
            declarations: [ CPComponent ],
            imports: [CommonModule, CookieModule.forRoot()],

        });
        TestBed.compileComponents();
        fixture = TestBed.createComponent(CPComponent);
    });

 it('should close the banner', () => {
        component.close();
        const comp = fixture.componentInstance;
        fixture.detectChanges();
        de = fixture.debugElement.query(By.css('.bwc-o-display-2'));
        el = de.nativeElement;
        expect(el.textContent).toBeUndefined();
      });

我的关闭方法

close() {
    this.cpBanner = false;
    this.cookieService.put( 'CP_BANNER', 'true' );
  }

请告诉我我在做什么错了。

2 个答案:

答案 0 :(得分:0)

从未分配变量component。您还必须更改执行顺序。试试这个:

it('should close the banner', () => {
    component = fixture.componentInstance; // assign component
    component.close(); // use component
    fixture.detectChanges();
    de = fixture.debugElement.query(By.css('.bwc-o-display-2'));
    expect(de).toBeFalsy();
});

答案 1 :(得分:0)

与其他答案一样,我怀疑原始错误是因为您尚未分配组件。除此之外,在我做出期望之前,我将等待过程stable

it('should close the banner', () => {
component = fixture.componentInstance; // assign component
component.close(); // use component
fixture.detectChanges(); // good for dectecting chenges
de = fixture.debugElement.query(By.css('.bwc-o-display-2'));
el = de.nativeElement;
fixture.whenStable().then(() => { // wait until the fixture is stable
   expect(el.textContent).toBeUndefined();
});
});