首页 > 解决方案 > 如何以角度测试组件@Input?

问题描述

我已经做了很多次没有问题,但由于某种原因,我无法让它工作。在我的组件中,我有一个 input @Input data: Data,在我的模板中,我使用该 input 有条件地显示或隐藏内容。由于某些原因,在我的测试中,即使我直接使用 设置组件,组件也不会注册数据存在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();
    });
  }

数据组件.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]"

标签: javascriptangulartypescriptjasminekarma-jasmine

解决方案


我想这可能是因为你打电话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();
    });
  }

推荐阅读