如何编写将检查父组件属性的测试用例?



>父组件:

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);
});

要一起测试两个组件,您必须在同一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();,而不是在调用方法时;这有助于将行为实现分开,允许您重命名内部方法,而无需更新测试。

最新更新