【问题标题】:Unit test, try to trigger ngOnchange methods Jasmine单元测试,尝试触发 ngOnchange 方法 Jasmine
【发布时间】:2020-09-22 18:52:40
【问题描述】:

我正在这里测试这个功能:

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

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

【问题讨论】:

    标签: angular unit-testing jasmine onchange


    【解决方案1】:

    很抱歉发布到旧线程。我的回答很可能不再与 PO 相关,但希望对其他有类似问题的人有所帮助。

    通过在每次测试之前重新配置testBed,我设法让ngOnChanges 响应fixture.detectChanges

      beforeEach(() => {
        TestBed.configureTestingModule({
          declarations: ...,
          providers: ...,
        }).compileComponents();
    
        fixture = TestBed.createComponent(TestComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });
    

    如果有更好的解决方案,将很高兴听到。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 它不会改变结果,因为我只触发一次夹具检测到变化
      • 有趣。我猜ngOnChanges 只有在我们显式调用它或者我们将组件包装在主机组件中并输入输入时才会在单元测试中被调用。 medium.com/@christophkrautz/…
      猜你喜欢
      • 1970-01-01
      • 2018-02-15
      • 2021-01-02
      • 2018-08-31
      • 2017-04-04
      • 2013-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多