【问题标题】:How to write a test case which will check parent component property?如何编写一个检查父组件属性的测试用例?
【发布时间】:2017-09-29 17:56:32
【问题描述】:

父组件:

export class PlayerListComponent {
  flag = false;
}

子组件:

export class PlayerAddComponent {
  @Output() notifyParent: EventEmitter<any> = new EventEmitter();

  clkCancle() {
    this.notifyParent.emit(false);
    // this will set parent component property 'flag' to false.
  }
}

现在如何在 Jasmine 规范文件中编写测试用例?

it('cancel button click should set flag to false', function () {
  // Act
  component.clkCancle();

  // Assert 
  // Since component do not have flag property. It will be set in parent while by Emitter.
  expect(???).toBe(false);
});

【问题讨论】:

  • "这会将父组件属性 'flag' 设置为 false" - 不会,这不是 的工作。孩子只是发出,您可以在孩子单元测试中进行测试;由 父母 酌情作出回应。如果您想同时测试这两个组件,请在 TestBed 中声明 both 并实例化父组件。
  • 您在测试中创建了一个组件,该组件具有像&lt;player-add (notifyParent)="flag = $event"&gt;&lt;/player-add&gt; 这样的模板,并且您测试了,当单击取消按钮时,组件的标志确实设置为 false。或者,如果您想测试父组件及其子组件的集成,您可以在测试中使用实际的父组件。
  • 我已经为子组件编写了我的规范文件,并在父组件中使用下面的 html 来绑定它。
  • “我已经为子组件编写了我的规范文件” - 然后,如上所述,您应该只测试该值是否正在发出。结果是什么不是孩子的问题。
  • @KiranChuahan 我的回答有帮助吗?你还有问题吗?

标签: angular jasmine karma-runner karma-jasmine


【解决方案1】:

要同时测试两个组件,您必须在同一个TestBed 中加载这两个组件。例如:

describe('component interaction', () => {
  let fixture: ComponentFixture<PlayerListComponent>;
  let component: PlayerListComponent;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [PlayerListComponent, PlayerAddComponent],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(PlayerListComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should set the parent flag when the child method is called', () => {
    // Arrange
    const child: PlayerAddComponent = fixture.debugElement
      .query(By.directive(PlayerAddComponent))
      .componentInstance;

    // Act
    child.clkCancle();  // ...Cancel?
    fixture.detectChanges();

    // Assert
    expect(component.flag).toBe(false, 'parent flag should be set');
  }
});

否则,您应该只测试孩子是否在正确的时间发射,因为这不应该是孩子的责任的一部分,因此会发生什么(这种行为可能会在不改变孩子的情况下改变,或者有所不同取决于孩子在哪里使用):

it('should emit when the method is called', done => {
  component.clkCancle();  // here component is PlayerAddComponent

  component.notifyParent.subscribe(flag => {
    expect(flag).toBe(false, 'should emit false');
    done();
  });
});

请注意,在这两种情况下,我都建议您测试当您单击按钮时会发生这种情况,例如使用fixture.nativeElement.querySelector('...').click();,而不是在调用方法时;这有助于将行为实现分开,允许您重命名内部方法而无需更新测试。

【讨论】:

    猜你喜欢
    • 2017-02-04
    • 1970-01-01
    • 1970-01-01
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    • 2019-04-13
    相关资源
    最近更新 更多