我有这个测试。在那里我设置了我的组件的一些值。这些值确定按钮的状态。在fixture.detectChanges()之前,仍然设置了这些值。但是(在const createButton ....之后)这些值已经消失并再次设置为null。问题是为什么以及如何设置这些值,以便我能够检测到按钮状态的更改。
it('should activate the create button with a customer and service set', () => {
fixture = TestBed.createComponent(MyComponent);
fixture.componentInstance.entry.service = new Service('1', 'Name', null);
fixture.componentInstance.entry.customer = customerMock;
fixture.detectChanges();
const createButton = fixture.debugElement.query(By.css('p-button[name="createButton"]'));
const actual = createButton.attributes['ng-reflect-disabled']; // TODO try find better way
expect(actual).toBe('false');
});
编辑:作为要求。我不能发布整个组件,但我认为组件的相关部分是onInit。
ngOnInit() {
this.servicePoolSubscription = this.stateService.getServiceSubject()
.subscribe(serviceList => this.services = serviceList);
this.Entry = EntryService.prepare();
}
ngOnDestroy(): void {
if (this.serviceSubscription) {
this.serviceSubscription.unsubscribe();
}
}
正如我想的那样。 EntryService.prepare()准备一个新对象。 fixture.detectChanges是否会再次触发onInit?
第一个fixture.detectChanges()
触发ngOnInit()
。在更改组件属性之前,首次调用它。