【发布时间】:2015-08-14 08:55:23
【问题描述】:
我试图监视控制器中定义的方法,但无论我做什么,我都会看到测试失败并显示以下消息:
错误:预期是间谍,但得到了函数。
我将 Karma、Jasmine 和 Sinon 与 Angular 一起使用。我很确定一切设置正确,因为只从 $scope 读取属性的测试通过了。
例如,我有一个非常简单的应用模块:
angular.module('app', []);
还有这个非常简单的控制器:
angular.module('app').controller('myController', ['$scope', function($scope) {
$scope.test = '';
$scope.setTest = function (newString) {
$scope.test = newString || 'default';
}
$scope.updateTest = function (newString) {
$scope.setTest(newString);
};
}]);
我的spec文件如下:
describe('myController', function () {
'use strict';
beforeEach(module('app'));
var $scope, sandbox;
beforeEach(inject(function ($controller) {
$scope = {};
$controller('myController', { $scope: $scope });
sandbox = sinon.sandbox.create();
}));
afterEach(function () {
sandbox.restore();
});
describe('#updateTest()', function () {
beforeEach(function () {
sandbox.spy($scope, 'setTest');
});
it('updates the test property with a default value', function () {
$scope.updateTest();
expect($scope.test).toEqual('default');
});
it('calls the setTest method', function () {
$scope.updateTest();
expect($scope.setTest).toHaveBeenCalled();
});
});
});
第一个测试(它只是检查测试属性是否更新)通过。
第二个测试,我只想监视 setTest() 方法,失败并显示上面的错误消息。
如果我在beforeEach 中注销$scope,我可以看到setTest 方法并且没有脚本错误。
我错过了什么?
【问题讨论】: