问题描述
我有一个在实例变量上使用 @Input()
注释的组件,我正在尝试为 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
和 ProductThumbnail
类中的任何其他字段 可以 使用这种方法是私有的(这是我喜欢它的主要原因超过蒂埃里的方法,尽管它有点冗长).
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).
这篇关于Angular2 单元测试与@Input()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!