我正在使用 Jasmine/Karma 进行单元测试,并且是这些框架的新手。在 Controller 中,我使用 ngDialog 进行模型显示,并且我想要 Controller 调用 ngDialog 的单元测试用例。 Controller :
(function () {
'use strict';
angular.module('app')
.controller('myController', MyController);
CongratulationsController.$inject = ['$scope',
'$rootScope',
'ngDialog'];
function CongratulationsController($scope, $rootScope, ngDialog) {
$scope.myData = {name: 'test',
grade: '5'};
$scope.modal1 = function() {
ngDialog.open({ template: 'views/modal/modal-1html',
className: 'ngdialog-theme-default',
controller: 'ModalController',
scope: $scope});
};
$scope.modal2 = function() {
ngDialog.open({ template: 'views/modal/modal-2html',
className: 'ngdialog-theme-default',
controller: 'ModalController',
scope: $scope});
};
}
}());
这是我的单元测试:
'use strict';
describe('Controller: MyController', function () {
var MyController,location, scope, ngDialogInstance;
ngDialogInstance = {
open: jasmine.createSpy('ngDialogInstance.open'),
dismiss: jasmine.createSpy('modalInstance.dismiss')
};
// load the controller's module
beforeEach(module('app'));
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $location, $rootScope, _ngDialog_) {
scope = $rootScope.$new();
MyController= $controller('myController', {$scope: scope ,
_ngDialog_: ngDialogInstance
});
location = $location;
spyOn(scope, 'openModal1');
}));
it('test controller exists', function () {
expect(!!MyController).toBe(true);
});
it('test controller calls ng dialog when it calls openModel method', function () {
scope.openModal1();
expect(scope.openModal1).toHaveBeenCalled();
expect(ngDialogInstance.open).toHaveBeenCalled();
});
});
当我运行以上测试用例时,出现以下错误。 它在预期 spy ngDialogInstance.open 被调用时失败。
谁能帮我解决这个问题吗?
最佳答案
这应该是,
it('test controller calls ng dialog when it calls openModel method', function () {
ngDialogInstance.open();
scope.openModal1();
expect(scope.openModal1).toHaveBeenCalled();
expect(ngDialogInstance.open).toHaveBeenCalled();
});
您必须包含以下行:
ngDialogInstance.open();
关于javascript - 如何使用 Jasmine 在单元测试中调用 ngDialog.open,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37888517/