我已经读过这个post (和其他的),但是我没有设法使这个简单的单元测试工作起来。我在用茉莉花的第二版。我的工厂很简单:
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是否已被调用(只有一次)?
发布于 2015-05-02 10:26:03
您的代码有两个主要问题。
首先,在设置间谍之前执行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 (使用茉莉花1.3,但这个示例中唯一的不同之处是,在茉莉花2中称为and.returnValue,在茉莉花1.3中称为returnValue )。
https://stackoverflow.com/questions/29994090
复制相似问题