angularjs - 如何从控制器监视服务方法?
问题描述
我正在为控制器编写 UT,在尝试实现 commandRouter.execute 方法(请参阅第二规范)时,我收到错误消息:无法读取未定义的属性“执行”。
有人可以让我知道我在这里做错了什么以及从控制器监视方法的正确方法是什么。?
module.controller('DcsPlus.AP.OmsControl.omsMasterRecipeDialogPopUpController', omsMasterRecipeDialogPopUpController);
omsMasterRecipeDialogPopUpController.$inject = [
'DcsPlus.Frame.Logic.commandRouter'
];
function omsMasterRecipeDialogPopUpController(commandRouter) {
var vm = this;
vm.execute = function(command) {
commandRouter.execute(command);
};
}
控制器.spec.js
describe('omsMasterRecipeDialogPopUpController', function () {
var omsMasterRecipeDialogPopUpControllerTest;
var commandRouterMock;
var $scope;
beforeEach(function () {
registerMockServices();
prepareCommandRouterMock();
});
describe('execute', function () {
it('1. Should check if execute method is defined', function() {
expect(omsMasterRecipeDialogPopUpControllerTest.execute).toBeDefined();
});
it('2. Should check if execute method of commandRouter is called', function() {
omsMasterRecipeDialogPopUpControllerTest.execute();
expect(commandRouterMock.execute).toHaveBeenCalled();
});
});
function prepareCommandRouterMock() {
commandRouterMock = {
execute: function() {
}
};
}
/*beforeEach(function () {
commandRouterMock = jasmine.createSpyObj('DcsPlus.Frame.Logic.commandRouter', ['execute']);
});*/
function registerMockServices() {
angular.mock.module('DcsPlus.AP.OmsControl', function ($provide) {
$provide.value('DcsPlus.Frame.Logic.commandRouter', commandRouterMock);
});
angular.mock.inject(['$controller', '$rootScope', 'dialogService',
function ($controller, $rootScope, dialogService) {
$scope = $rootScope.$new();
spyOn(commandRouterMock, 'execute').and.callThrough();
// Init the controller, passing our spy service instance
omsMasterRecipeDialogPopUpControllerTest = $controller('DcsPlus.AP.OmsControl.omsMasterRecipeDialogPopUpController', {
$scope: $scope
});
}]);
}
});
解决方案
一开始您创建commandRouterMock
但从不将其分配给任何东西。
尝试这个:
beforeEach(function () {
registerMockServices();
commandRouterMock = prepareCommandRouterMock();
});
function prepareCommandRouterMock() {
return {
execute: function() {
}
};
}
推荐阅读
- r - 在分隔符处拆分列,用拆分中的值填充新列
- reactjs - React redux + react-loadable ...如何使其工作?
- android - Android Google Drive REST API 离线缓存
- python-3.x - Luigi Pipeline in Dockerfile; unknown instruction PYTHONPATH
- c# - 悬停时如何更改按钮的边框颜色(c# | Visual Studio)
- node.js - 当尝试将变量传递给另一个模块时,将代码拆分到Nodejs中的自定义模块时,它会变得未定义
- c++ - 非法操作stringstream << stringstream与c ++ 11
- node.js - 如何在 Node.js 的 Handlbars 中检查数字的值?
- python - 从 Gunicorn/Nginx WSGI API 权限错误运行 Docker SDK
- redirect - 如何在 Shopify 中强制所有 URL 都带有斜杠