Unit test, try to trigger ngOnchange methods Jasmine

Viewed 3748

I'm trying to test this function here :

ngOnChanges(): void {
    if (this.isCustomer) {
      let sectionCopy = [...this.sections];
      this.sectionsNotFilled = sectionCopy.find(section => section.filled === false);
...
    }
}

I saw on a lot of ressource that in order to trigger ngOnChanges, I have to use fixture.detectChanges();, but i still can not test and got the wrong result on my test:

...
let component: XXX;
let fixture: ComponentFixture<XXX>;
...
const sections = [
  {
    key: 'SECTION1',
    name: 'Section 1',
    filled: true
  },
  {
    key: 'SECTION2',
    name: 'Section 2',
    filled: false
  }
];

...

it('should do test', () => {
    const sectionsMock = {...sections};
    component.sections = sectionsMock;
    component.isCustomer = true;

    console.log(component.sections); => section are here
    //trigger

    fixture.detectChanges();

    console.log(component.sectionsNotFilled);

    expect(component.sectionsNotFilled).toBe(true); => return false :/
  });

Any ideas? Did I did something wrong?

2 Answers

Sorry for posting to an old thread. Most likely my answer is no longer relevant for the PO, but hopefully, it will be helpful for other people who have a similar question.

I managed to get ngOnChanges respond to fixture.detectChanges by reconfiguring the testBed before each test:

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: ...,
      providers: ...,
    }).compileComponents();

    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

Will be happy to hear out if there are better solutions.

The ngOnChanges gets triggered on the first fixture.detectChanges() and not subsequent ones.

beforeEach(() => {
  fixture = TestBed.createComponent(XXX);
  component = fixture.componentInstance;
  const sectionsMock = {...sections};
  component.sections = sectionsMock;
  component.isCustomer = true; // set isCustomer = true here
  fixture.detectChanges(); // call fixture.detectChanges() here to go to ngOnChanges()
                           // and the line above will ensure that it goes inside of the if block

});

it('should do test', () => {
  expect(component.sectionsNotFilled).toBeTruthy(); // I think you need toBeTruthy() here
                                                    // because I think sectionsNotFilled resolves into an object.
});
Related