Issue
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.
How do I setup my Jasmine test so that a mocked product is injected (provided?) and I can test the openProductPage()
method?
My component:
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}]);
}
}
Solution
I usually do something like:
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
}
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).
Answered By - drew moore
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.