【问题标题】:Unit test angular @Input() with get set带有设置的单元测试角度@Input()
【发布时间】:2018-06-17 21:58:27
【问题描述】:

我正在使用与Angular2 @Input to a property with get/set 类似的@Input。不过,我在弄清楚如何设置单元测试时遇到了一些麻烦。这是我的组件

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)

我最初的目的是创建一个模拟订单常量,并将其分配给我的组件中的 a before each like so...

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

但是,我不能做那个任务

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

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

【问题讨论】:

  • 你得到的最后一个错误很奇怪,因为该属性不是只读的。如果没有看到组件的完整代码和测试,很难评论第一个。无论如何,您不需要 OrdersGridComponent 作为父级。不过,您可能需要一个父组件,但它不需要是 OrdersGridComponent。任何使用 OrderDetailsComponent 的测试组件都可以。也不清楚为什么你有一个 getter 和一个 setter,因为它们不会做任何普通公共财产会做的事情。
  • @JBNizet getter 和 setter 是一个很好用的问题。我没有编写组件的那一部分,所以希望我可以重构它。但是父组件是否只是我要模拟的主机?
  • 这将是一个专门为您的测试编写的组件,具有您需要能够测试 OrderDetailsComponent 的模板和状态。类似这样的东西:github.com/Ninja-Squad/globe42/blob/master/frontend/src/app/…,用于测试带有有效输入的图表组件。

标签: angular unit-testing angular-test


【解决方案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-19
    • 2018-09-04
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多