【问题标题】:How can I test component @Input in angular?如何以角度测试组件@Input?
【发布时间】:2021-05-06 20:01:46
【问题描述】:

我已经做了很多次,没有任何问题,但由于某种原因,我无法让它工作。在我的组件中,我有一个输入 @Input data: Data,在我的模板中,我使用该输入有条件地显示或隐藏内容。由于某些原因,在我的测试中,即使我直接使用component.data = {props: values} 设置它,组件也不会注册数据存在,但是如果我使用fit 单独运行测试,它们运行良好。

data.component.spec.ts

  beforeEach(() => {
    fixture = testbed.createComponent(DataComponent);
    component = fixture.componentInstance;
    component.data = {values: ['a', 'b', 'c']};
    fixture.detectChanges();
    component.ngOnInit();
    fixture.detectChanges();
  });

  describe('when viewing', () => {
    it('should load and display data', () => {
      const el = fixture.debugElement.query(By.css('[data-content]'));
      expect(el).toBeTruthy();
    });
  }

data.component.ts

export class DataComponent implements OnInit {
  @Input() data!: Data;

  constructor() {};
  
  ngOnInit() {
    console.log('init');
  }
}

data.component.html

<div *ngIf="data.values.length">
  <p data-content *ngFor="let value of data.values">{{value}}</p>
</div>

我遇到的错误: Expected null to not be null "[data-content]"

【问题讨论】:

  • 您是否将 CommonModule 导入到您的测试中,以便 ngIf 指令可用?
  • @rook218 我是,是的。

标签: javascript angular typescript jasmine karma-jasmine


【解决方案1】:

我想这可能是因为你打电话给fixture.detectChangesngOnInit。您拨打的第一个fixture.detectChanges,为您拨打ngOnInit

试试这个:

  beforeEach(() => {
    fixture = testbed.createComponent(DataComponent);
    component = fixture.componentInstance;
    component.data = {values: ['a', 'b', 'c']};
    fixture.detectChanges(); // => this will call ngOnInit
    // component.ngOnInit(); // remove this line, the first fixture.detectChanges()
    // calls ngOnInit for you.
  });

  describe('when viewing', () => {
    it('should load and display data', () => {
      const el = fixture.debugElement.query(By.css('[data-content]'));
      expect(el).toBeTruthy();
    });
  }

【讨论】:

  • 没有变化。这似乎也是随机失败。有时 1 或 2 个测试会通过,有时它们会全部失败,即使没有进行代码更改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-22
  • 2016-07-02
相关资源
最近更新 更多