微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决单元测试,尝试触发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.
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。