Mocking $modal in AngularJS unit tests

前端 未结 4 1353
你的背包
你的背包 2020-11-27 11:30

I\'m writing a unit test for a controller that fires up a $modal and uses the promise returned to execute some logic. I can test the parent controller that fire

4条回答
  •  孤城傲影
    2020-11-27 12:00

    Since modals use promises you should definitely use $q for such things.

    Code becomes:

    function FakeModal(){
        this.resultDeferred = $q.defer();
        this.result = this.resultDeferred.promise;
    }
    FakeModal.prototype.open = function(options){ return this;  };
    FakeModal.prototype.close = function (item) {
        this.resultDeferred.resolve(item);
        $rootScope.$apply(); // Propagate promise resolution to 'then' functions using $apply().
    };
    FakeModal.prototype.dismiss = function (item) {
        this.resultDeferred.reject(item);
        $rootScope.$apply(); // Propagate promise resolution to 'then' functions using $apply().
    };
    
    // ....
    
    // Initialize the controller and a mock scope
    beforeEach(inject(function ($controller, $rootScope) {
        scope = $rootScope.$new();
        fakeModal = new FakeModal();
        MainCtrl = $controller('MainCtrl', {
            $scope: scope,
            $modal: fakeModal
       });
    }));
    
    // ....
    
    it("should cancel the dialog when dismiss is called, and  $scope.canceled should be true", function () {
        expect( scope.canceled ).toBeUndefined();
    
        fakeModal.dismiss( "cancel" ); //Call dismiss (simulating clicking the cancel button on the modal)
        expect( scope.canceled ).toBe( true );
    });
    

提交回复
热议问题