sim*_*sen 33 unit-testing angularjs
我正在尝试创建一个简单的单元测试来测试我的show函数.
我收到以下错误:
TypeError: Object #<Object> has no method 'show'
Run Code Online (Sandbox Code Playgroud)
好像$rootScope不是控制器的范围?
这是我的控制器:
function OpponentsCtrl($scope, $location) {
$scope.show = function(url) {
$location.path(url);
}
}
OpponentsCtrl.$inject = ['$scope', '$location'];
Run Code Online (Sandbox Code Playgroud)
这是我的控制器单元测试:
describe('OpponentsCtrl', function() {
beforeEach(module(function($provide) {
$provide.factory('OpponentsCtrl', function($location){
// whatever it does...
});
}));
it('should change location when setting it via show function', inject(function($location, $rootScope, OpponentsCtrl) {
$location.path('/new/path');
$rootScope.$apply();
expect($location.path()).toBe('/new/path');
$rootScope.show('/test');
expect($location.path()).toBe('/test');
}));
});
Run Code Online (Sandbox Code Playgroud)
sim*_*sen 64
这就是我的测试最终工作的方式.
describe('OpponentsCtrl', function() {
var scope, rootScope, ctrl, location;
beforeEach(inject(function($location, $rootScope, $controller) {
location = $location;
rootScope = $rootScope;
scope = $rootScope.$new();
ctrl = $controller(OpponentsCtrl, {$scope: scope});
}));
it('should change location when setting it via show function', function() {
location.path('/new/path');
rootScope.$apply();
expect(location.path()).toBe('/new/path');
// test whatever the service should do...
scope.show('/test');
expect(location.path()).toBe('/test');
});
});
Run Code Online (Sandbox Code Playgroud)
fel*_*ekm 20
为什么不简单地使用spyOn函数?
describe('OpponentsCtrl', function() {
var location;
beforeEach(module(function($provide) {
$provide.factory('OpponentsCtrl', function($location){
location = $location;
});
}));
it('should change location when setting it via show function', inject(function() {
spyOn(location, 'path');
expect(location.path).toHaveBeenCalledWith('/new/path');
}));
});
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
23976 次 |
| 最近记录: |