Angular2 单元测试与@Input()

新手上路,请多包涵

我有一个在实例变量上使用 @Input() 注释的组件,我正在尝试为 openProductPage() 方法编写单元测试,但我有点迷失了我如何设置我的单元测试。我 可以 公开那个实例变量,但我认为我不应该诉诸于此。

如何设置我的 Jasmine 测试以便注入模拟产品(提供?)并且我可以测试 openProductPage() 方法?

我的组件:

 import {Component, Input} from "angular2/core";
import {Router} from "angular2/router";

import {Product} from "../models/Product";

@Component({
    selector: "product-thumbnail",
    templateUrl: "app/components/product-thumbnail/product-thumbnail.html"
})

export class ProductThumbnail {
    @Input() private product: Product;

    constructor(private router: Router) {
    }

    public openProductPage() {
        let id: string = this.product.id;
        this.router.navigate([“ProductPage”, {id: id}]);
    }
}

原文由 hartpdx 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 540
2 个回答

我通常会做类似的事情:

 describe('ProductThumbnail', ()=> {
  it('should work',
    injectAsync([ TestComponentBuilder ], (tcb: TestComponentBuilder) => {
      return tcb.createAsync(TestCmpWrapper).then(rootCmp => {
        let cmpInstance: ProductThumbnail =
               <ProductThumbnail>rootCmp.debugElement.children[ 0 ].componentInstance;

        expect(cmpInstance.openProductPage()).toBe(/* whatever */)
      });
  }));
}

@Component({
 selector  : 'test-cmp',
 template  : '<product-thumbnail [product]="mockProduct"></product-thumbnail>',
 directives: [ ProductThumbnail ]
})
class TestCmpWrapper {
    mockProduct = new Product(); //mock your input
}

请注意, productProductThumbnail 类上的任何其他字段 可以使用这种方法私有(这是我喜欢它而不是蒂埃里方法的主要原因,尽管它有点更多详细)。

原文由 drew moore 发布,翻译遵循 CC BY-SA 3.0 许可协议

这是来自官方文档 https://angular.io/docs/ts/latest/guide/testing.html#!#component-fixture 。因此,您可以创建新的输入对象 expectedHero 并将其传递给组件 comp.hero = expectedHero

还要确保最后调用 fixture.detectChanges(); ,否则属性将不会绑定到组件。

工作示例

// async beforeEach
beforeEach( async(() => {
    TestBed.configureTestingModule({
        declarations: [ DashboardHeroComponent ],
    })
    .compileComponents(); // compile template and css
}));

// synchronous beforeEach
beforeEach(() => {
    fixture = TestBed.createComponent(DashboardHeroComponent);
    comp    = fixture.componentInstance;
    heroEl  = fixture.debugElement.query(By.css('.hero')); // find hero element

    // pretend that it was wired to something that supplied a hero
    expectedHero = new Hero(42, 'Test Name');
    comp.hero = expectedHero;
    fixture.detectChanges(); // trigger initial data binding
});

原文由 Vazgen Manukyan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进