我试图窥探在控制器中定义的方法工作,但无论我做什么,我看到测试失败与消息:间谍不是角,茉莉花和兴农
Error: Expected a spy, but got Function.
我使用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);
};
}]);
我的规格文件如下:
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()
方法,失败并显示上面的错误消息。
如果我注销$scope
在beforeEach
我可以看到setTest
方法,并且没有脚本错误。
我错过了什么?
辉煌,我忘了这个包!我将安装它并尝试使其工作。我以前面例子中的方式使用了Karma/Jasmine/Sinon,但我并没有参与设置.... – danwellman
是的,就是这样,谢谢先生!另外,我必须通过将它添加到Karma加载的文件列表中来加载Karma中的文件。 – danwellman