单元测试,尝试触发ngOnchange方法Jasmine

问题描述

我正在这里测试此功能

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

我在很多资源上都看到,为了触发ngOnChanges,我必须使用fixture.detectChanges();,但是我仍然无法测试并在测试中得到错误的结果:

...
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 :/
  });

有什么想法吗?我做错什么了吗?

解决方法

ngOnChanges是在 第一个 fixture.detectChanges()而不是随后的那个触发的。

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