我有一个带有控制器的Angular应用程序,它在函数调用期间显示Angular-Strap模态窗口.它在Chrome中正常运行,但我无法进行有效的单元测试.
App模块和FooController:
var app = angular.module("app",["mgcrea.ngStrap"]); app.controller("FooController",function($scope,$modal) { var fooModal = $modal({ title: 'Foo',content:'Bar',show: false,html: true,backdrop: 'static',placement: 'center'}); angular.extend($scope,{ makeItFoo: function() { fooModal.show(); } }); });
控制器规格:
describe('FooController',function () { var scope,controller,modal; beforeEach(module('app',function ($provide) { // Stub out $modal service $provide.value('$modal',function () { return { hide: function () { },show: function () { } }; }); })); beforeEach(inject(function ($rootScope,$controller,$injector) { //set up a new scope and the controller for the test scope = $rootScope.$new(); controller = $controller('FooController',{$scope: scope}); modal = $injector.get('$modal'); })); it('should show the modal',function () { var modalSpy = spyOn(modal(),'show'); scope.makeItFoo(); expect(modalSpy).toHaveBeenCalled(); }); });
我希望我调用makeItFoo()来显示模态,但Jasmine未通过测试,错误预期间谍节目被调用.我也尝试将模态的show属性设置为true而不是单独调用show(),并且我尝试了其他变体来存储$modal服务并将其直接注入控制器,但它最终都是相同的错误.
我正在使用AngularJS 1.2.14,Angular-Strap 2.0.0和Jasmine 1.3.1.
解决方法
而不是做这些.使用show和hide方法为$modal创建一个模拟对象,并设置对它们的期望.
describe('FooController',modal; beforeEach(module('app')); beforeEach(inject(function ($rootScope,$controller) { //set up a new scope and the controller for the test scope = $rootScope.$new(); //Create spy object modal = jasmine.createSpyObj('modal',['show','hide']); //provide modal as dependency to the controller. controller = $controller('FooController',{$scope: scope,$modal:modal}); })); it('should show the modal',function () { scope.makeItFoo(); expect(modal.show).toHaveBeenCalled(); }); });
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。