【问题标题】:How to test void method that changes class variable in Angular如何测试在Angular中更改类变量的void方法
【发布时间】:2019-09-02 07:37:20
【问题描述】:

我不习惯测试或编写 Angular 代码,所以我想知道如何测试返回 void 并更改类变量的方法(在本例中为 changeMyMonth)?

date: Date = new Date();
private dateArray: Date[];

private getMaxDaysInMonth(): number {
  return new Date(this.date.getFullYear(), this.date.getMonth() + 1, 0).getDate();
}

changeMyMonth(amount: number): void {
  this.date= new Date(
    this.date.getFullYear(),
    this.date.getMonth() + amount, 1);
  this.dateArray= this.getArrayOfDates(this.getMaxDays(), this.date);
}

【问题讨论】:

    标签: angular unit-testing jestjs


    【解决方案1】:
    beforeEach(() => {
        fixture = TestBed.createComponent(ComponentName);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });
    
    it('should test changeMyMonth', () => {
        component.changeMyMonth(3);
        fixture.detectChanges();
    
        expect(component.date).toEqual(/* something */);
        expect(component['dateArray']).toEqual(/* something */);
    });
    
    it('should test changeMyMonth', () => {
        let returnValue = component['getMaxDaysInMonth']();
    
        expect(returnValue).toEqual(/* something */);
    });
    

    【讨论】:

      【解决方案2】:

      不是很漂亮,但您可以通过使用强制转换“绕过”Typescript 检查来访问私有字段;

      let valueToCheck = (<any>yourComponent).dateArray;
      

      private 修饰符对转译的 javascript 代码没有影响。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-24
        • 2019-04-21
        • 2015-06-16
        • 2019-11-25
        相关资源
        最近更新 更多