javascript – 用Jasmine单元测试$modal

前端之家收集整理的这篇文章主要介绍了javascript – 用Jasmine单元测试$modal前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个带有控制器的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();
    });
});

Here’s a fiddle as well.

我希望我调用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();
    });
});

猜你在找的JavaScript相关文章