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}]);
}
}
this is from official documentation https://angular.io/docs/ts/latest/guide/testing.html#!#component-fixture. So you can create new input object expectedHero and pass it to the component comp.hero = expectedHero
Also make sure to call fixture.detectChanges();
last, otherwise property will not be bound to component.
Working Example
// 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
});