TypeError:mat-option的fixture.debugElement.query为空

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

我是Angular的新手,正在使用Karma进行测试。我正在尝试从模板中获取mat-options的实例,以验证其文本内容。不幸的是,我收到因果报应的null错误

TypeError:optionDe在...中为null]

这里是测试代码:

// When option is selected to [1], set selected to that:
  it(
    'Should select Shoes Order Type: International',
    () => {
      const de: DebugElement = fixture.debugElement;
      const optionDe = de.query(By.css('mat-option'));
      const p: HTMLElement = optionDe.nativeElement;
      expect(p.textContent).toEqual(''); 
    }
  );

这是模板代码:

<mat-form-field>
    <mat-label>Order-Type:</mat-label>
    <mat-select>
        <mat-option
            *ngFor="let type of orderTypes"
            [value] = "type.name">
            {{ type.name }}
        </mat-option>
    </mat-select>
</mat-form-field>

问题:

如何正确获取该mat-option或模板中任何字段的引用,以免出现空指针异常并在测试中使用其属性?

angular-material karma-jasmine
1个回答
0
投票

当然是。您没有在共享的代码中初始化任何数据。尝试这样的事情。

// When option is selected to [1], set selected to that:
it('Should select Shoes Order Type: International',
() => {
  // initialize the data in your component 
  fixture.component.orderTypes = [mockData];
  const de: DebugElement = fixture.debugElement;
  const optionDe = de.query(By.css('mat-option'));
  const p: HTMLElement = optionDe.nativeElement;
  expect(p.textContent).toEqual(''); 
}
);
© www.soinside.com 2019 - 2024. All rights reserved.