Sebastian
Sebastian

Reputation: 470

Angular 2+ Unit Test - fixture.detectChanges() removes component properties

I have this test. In there i setup some values of my component. These values determine the status of a button. Right before fixture.detectChanges() those values are still set. But after (right at const createButton....) those values are gone and set to null again. Question is why and how can i set these values so that i am able to detect changes to the Button status.

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

  });

EDIT: As request. I cannot post the whole component, but I think the relevant part of the component is onInit.

ngOnInit() {
    this.servicePoolSubscription = this.stateService.getServiceSubject()
        .subscribe(serviceList => this.services = serviceList);
      this.Entry = EntryService.prepare();
  }

  ngOnDestroy(): void {
    if (this.serviceSubscription) {
      this.serviceSubscription.unsubscribe();
    }
  }

As i think about it. EntryService.prepare() prepares a new object. Does fixture.detectChanges trigger the onInit again?

Upvotes: 2

Views: 4303

Answers (1)

Normunds Kalnberzins
Normunds Kalnberzins

Reputation: 1245

the first fixture.detectChanges() triggers ngOnInit(). Call it first time before you change the component properties.

Upvotes: 6

Related Questions