Angular 2 v.2.0.0 - TS + karma + jasmine.
I test this function - back on click to previously page:
public isClick: boolean = false;
public backClicked(location: Location): void {
if (!this.isClick) {
this.isClick = true;
this.location.back();
}
}
And this is my test:
describe("NavBarComponent", () => {
describe("function backClicked(): void", () => {
let testNavBarComponent: NavBarComponent;
let loc: Location;
beforeEach(() => {
testNavBarComponent = new NavBarComponent(null);
});
loc = jasmine.createSpyObj("Location", ["back"]);
it ("It is backClicked() function test", () => {
testNavBarComponent.backClicked(loc);
expect(loc.back).toHaveBeenCalledTimes(1);
});
});
});
After i run the test, i've got this error: TypeError: Cannot read property 'back' of null
. Maybe problem with createSpyObj
, or somethig else?
In the backClicked function, you're calling the class instance of location
this.location
rather than the instance of location passed to the functionlocation
. I'm assuming that your NavBarComponent has Location injected due to the error message (by default, things are undefined rather than null).You could do something like the following:
Alternatively, I've had good luck using Angular's ReflectiveInjector class. The documentation and articles available for mocking dependencies for tests in Angular 2 is all over the board from having so many iterations of the RC,
so I'm not 100% sure this is considered a best practice:Edit: This can and should be accomplished using the TestBed.configureTestingModule now: https://blog.thoughtram.io/angular/2016/11/28/testing-services-with-http-in-angular-2.html
Using the ReflectiveInjector, you can also declare your dependencies in the same way you do in app.module. For example, mocking the Http service:
There's confusion in Angular between Location from
@angular/common
and DOM Location object which is available by default. Inspite of, Angular's version provides.go()
function, in fact, it only interacts with router and doesn't reload the page as DOM object do. So, for real browser interaction you have to use the DOM version, which brings you to a problem how to test this?Unfortunately, it's not possible to spy on because it's writable object. But you can inject it in your component as value. That's how it looks like
See https://angular.io/guide/dependency-injection#non-class-dependencies for details
To test in Angular (as in s-f's answer), you can inject the LOCATION_TOKEN into your TestBed, like this: