使用@Input()进行Angular2单元测试 [英] Angular2 unit test with @Input()
问题描述
我有一个在实例变量上使用 @Input()
注释的组件,我正在尝试为<$ c $编写单元测试c> openProductPage()方法,但我在设置单元测试方面有点迷失。我可以将该实例变量公开,但我认为我不应该诉诸于此。
I've got a component that uses the @Input()
annotation on an instance variable and I'm trying to write my unit test for the openProductPage()
method, but I'm a little lost at how I setup my unit test. I could make that instance variable public, but I don't think I should have to resort to that.
如何设置我的Jasmine测试以便注入模拟产品(提供?)并且我可以测试 openProductPage()
方法?
How do I setup my Jasmine test so that a mocked product is injected (provided?) and I can test the openProductPage()
method?
我的组件:
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}]);
}
}
推荐答案
我通常做类似的事情:
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
}
注意 product
和a ProductThumbnail
类上的其他字段可以使用这种方法是私有的(这是我比Thierry的方法更喜欢它的主要原因,尽管事实是它有点冗长)。
Note that product
and any other fields on the ProductThumbnail
class can be private with this approach (which is the main reason I prefer it over Thierry's approach, despite the fact that it's a little more verbose).
这篇关于使用@Input()进行Angular2单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!