Angularjs:使用spyOn模拟location.path()进行单元测试

时间:2015-05-01 19:50:57

标签: angularjs unit-testing jasmine spyon

我已经阅读了这个post(和其他人),但我没有设法让这个简单的单元测试工作。我正在使用Jasmine的第2版。 我的工厂很简单:

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;
    });

我的单元测试也很简单:

'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');
    });
});

这没有通过测试(我得到的错误是假设为" home")。

我做错了什么? 有没有办法验证spyOn是否已被调用(只有一次)?

1 个答案:

答案 0 :(得分:10)

您的代码存在两个主要问题。

首先,在设置间谍之前执行getPath()功能。你应该在上一个beforeEach中设置间谍,或者在测试中注入你的工厂(我去了第二个解决方案)。

第二个问题(它还没有影响测试)是你用test的函数参数隐藏你的$location变量 - 你将无法访问它,因为它总是未定义的。删除此arg后,我可以测试是否使用expect(...).toHaveBeenCalled()调用了间谍。

这是一个有效的代码:

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

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

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

JSFiddle(使用Jasmine 1.3,但此示例中的唯一区别是您在Jasmine 2中调用and.returnValue,在Jasmine 1.3中调用returnValue

相关问题