Angular 2+单元测试 - fixture.detectChanges()删除组件属性

问题描述 投票:0回答:1

我有这个测试。在那里我设置了我的组件的一些值。这些值确定按钮的状态。在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?

angular unit-testing karma-jasmine
1个回答
1
投票

第一个fixture.detectChanges()触发ngOnInit()。在更改组件属性之前,首次调用它。

© www.soinside.com 2019 - 2024. All rights reserved.