2

我正在使用与 Angular2 @Input 类似的 @Input 到带有 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是子组件。但如果是这种情况,我看不到如何在我的单元测试中进行设置。任何反馈将不胜感激。

4

1 回答 1

1

我很确定魔法与async()

零件:

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

测试:

it('myVar input should set _myVar', async(() => {
  component.myVar = 42;
  expect(component._myVar).toBe(42);
}));
于 2019-02-14T14:18:49.627 回答