我正在使用 Controller 作为 Angular 的语法,我想使用 jasmine 和 sinon 测试我的代码。
假设我想要以下 Controller 代码:
angular
.module('Test')
.controller('TestController', TestController);
TestController.$inject = [];
function TestController() {
var viewModel = this;
viewModel.myFunction = myFunction;
function myFunction(){
//do something
//now call a helper function
helperFunction()
}
function helperFunction(){
// ....
}
}
我的问题是如何测试 helperFunction() 或什至对它进行监视?我的助手在我的测试中不可见。
这是我的测试:
(function () {
'use strict';
var myController;
describe('Test', function () {
beforeEach(module('Test'));
beforeEach(inject(function ($controller, $injector) {
myController = $controller('TestController');
}));
it('Tests helperFunction', function (){
var sinonSpy = sinon.spy(myController, 'helperFunction');
//perform the action
myController.myFunction();
//expect the function was called - once
expect(sinonSpy .callCount).toEqual(1);
}
})
})
最佳答案
您无法访问这些功能。当你定义一个命名的 JS 函数时,它等同于说:
var helperFunction = function(){};
在这种情况下,可以很清楚地看到 var 仅在 block 内的范围内,并且包装 Controller 没有对其进行外部引用。
要使函数可测试,您需要将其添加到 Controller 的 $scope 中。
viewModel.helperFunction = helperFunction;
但请注意,为了使其可测试而公开所有内容并不是一个好主意。您确实需要考虑测试它是否真的会为您的项目增加一些值(value)
关于javascript - 测试 javascript 函数 - Controller 不可见( Angular ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39410789/