尝试为我的控制器编写单元测试:
app.controller('StartGameCtrl', function ($scope, $timeout,$state) {
$scope.startGame = function () {
$scope.snap = false;
$scope.dealCards();
debugger;
$state.go('cpu');
}
});
我写了这个茉莉花单元测试:
describe('snap tests', function() {
beforeEach(module('snapApp'));
var scope, createController, state;
beforeEach(inject(function ($rootScope, $controller,$state) {
scope = $rootScope.$new();
createController = function () {
return $controller('StartGameCtrl', {
'$scope':scope,
'$state':state
});
};
}));
it('startGame should call dealcards', function () {
var controller = createController();
spyOn(scope, 'dealCards');
scope.startGame();
//expect(scope.dealCards).toHaveBeenCalled();
});
});
当我进行业力测试时,我收到一个错误:
TypeError: 'undefined' is not an object (evaluating '$state.go')
at startgamectrl.js:9
答案 0 :(得分:1)
您已将$state
本地分配为state
(规范中未定义的var),而不是注入的$state
服务。
不是这样做,而是为$state
创建一个间谍。例如......
beforeEach(inject(function ($rootScope, $controller) {
scope = $rootScope.$new();
state = jasmine.createSpyObj('$state', ['go']);
createController = function () {
return $controller('StartGameCtrl', {
'$scope':scope,
'$state':state
});
};
}));
然后你可以测试它被称为
expect(state.go).toHaveBeenCalledWith('cpu');