【问题标题】:Jasmine test case Cannot read property 'close' of undefinedJasmine 测试用例无法读取未定义的属性“关闭”
【发布时间】:2019-01-20 20:01:06
【问题描述】:

我尝试为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' );
  }

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

【问题讨论】:

  • 你在哪里定义变量component
  • 如果您在component.close() 收到错误,您的component 可能没有正确初始化。先检查一下。
  • 我已经添加了完整的代码,我在 vscode 中没有看到任何错误

标签: angular typescript jasmine karma-jasmine


【解决方案1】:

从未分配变量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();
});

【讨论】:

  • 谢谢,但我收到另一个错误TypeError: Cannot read property 'nativeElement' of null
  • 我猜对 close() 的调用会从 DOM 中删除 '.bwc-o-display-2'。所以关闭后没有 debugElement 也没有 nativeElement 。我会更新我的答案
猜你喜欢
  • 2018-12-09
  • 2023-03-29
  • 2018-12-23
  • 2019-12-24
  • 2021-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-17
相关资源
最近更新 更多