vendredi 1 mai 2015

Angularjs: mock location.path() with spyOn for a unit test

I have already read this post (and others) but I don't manage to make this simple unit test work. I'm using the version 2 of Jasmine. My factory is very simple:

angular.module('myApp')
    .factory('detectPath', function ($location, $rootScope) {
        'use strict';
        var locationPath = $location.path()
        function getPath () {
            if (locationPath === '/') {
                locationPath = 'home';
            } else {
                locationPath = '';
            }
            $rootScope.path = locationPath;
        }
        getPath();
        return locationPath;
    });

And my unit test is just as simple:

'use strict';
describe('Factory: detectPath', function () {
    var detectPath, $rootScope, $location;

    beforeEach(module('myApp'));
    beforeEach(inject(function (_detectPath_, _$rootScope_, _$location_) {
        detectPath = _detectPath_;
        $rootScope = _$rootScope_;
        $location = _$location_;
        spyOn($location, 'path').and.returnValue('/');
    }));

    it('should return pathName', function ($location) {
        expect($rootScope.path).toBe('home');
    });
});

This doesn't pass the test (I get the error expect false to be "home").

What I am doing wrong? Is there a way to verify that spyOn has been called (only once)?

Aucun commentaire:

Enregistrer un commentaire