使用get set设置单元测试角度@Input()

时间:2018-01-08 21:43:26

标签: angular unit-testing angular-test

我正在使用类似的@Input到Angular2 @Input to a property with get/set。我一直在努力弄清楚如何设置我的单元测试。这是我的组件

get order(): any {
    return this._order;
}

@Input()
set order(value: any) {

    this._order = value;
}

这是我的测试设置

 TestBed.configureTestingModule({
            declarations: [
                OrderDetailsComponent,
                OrdersGridComponent,
                KeyValuePipe
            ],
            schemas: [
                CUSTOM_ELEMENTS_SCHEMA
            ],
            providers: [
            ],
            imports: [
                // AppModule
            ]
        }).compileComponents();

在我定义组件的每个区域之前添加一个

beforeEach(() => {
    fixture = TestBed.createComponent(OrderDetailsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();  
});

在我可以运行这个简单的测试之前

 it("should set this.enable button to false", () => {
    component.signOrderFromOrderDetails();
    expect(component.signButtonEnable).toBe(false);
});

我收到错误

TypeError: undefined is not an object (evaluating 'this._order.hasOwnProperty') in karma-test-shim.js (line 106886)

我的首要任务是创建一个模拟订单常量并将其分配给我之前的组件,因此...

  const order = {
    orderSections: [],
    patient: {}
  };
 component.order = order;

但是,我不允许进行该作业

TypeError: Attempted to assign to readonly property. in karma-test-shim.js (line 94033)

我的下一个假设是我必须模拟父组件 OrdersGridComponent ,因为 OrdersDetails 是孩子。但如果是这种情况,我没有看到如何在我的单元测试中设置它。任何反馈都将非常感激。

1 个答案:

答案 0 :(得分:0)

我很确定async()的魅力在于

组件:

@Input()
set myVar(data: number) {
   this._myVar = data;
}

测试:

it('myVar input should set _myVar', async(() => {
  component.myVar = 42;
  expect(component._myVar).toBe(42);
}));