Material: How to Unit test controller containing $mdDialog?

Created on 12 Feb 2015  路  4Comments  路  Source: angular/material

I am unit testing an Angular controller with karma/Jasmine. The controller contains the $mdDialog service. How do I mock out $mdDialog?

Most helpful comment

beforeEach(function () {
    sinon.spy($mdDialog, 'show');
    controller = $controller(YourController);

    $rootScope.$apply();
});
describe('after button pressed', function() {
    it('should have dialog open', function () {
        controller.yourFunctionWithCallingDialog();

        expect($mdDialog.show).to.have.been.calledOnce;
    });
})

All 4 comments

Please post this in the Angular Material Forum

FWIW, I just did this today. Inject _$mdDialog_ and $q and set it in your controller.

I just extend the show() method with a dummy promise.

        _.extend(_$mdDialog_, {
            show: function(thing) {
                deferred = $q.defer();
                return deferred.promise;
            }
        });

In your test, just do this to get passed the promise.

        deferred.resolve();
        scope.$digest(); //  $mdDialog.show
beforeEach(function () {
    sinon.spy($mdDialog, 'show');
    controller = $controller(YourController);

    $rootScope.$apply();
});
describe('after button pressed', function() {
    it('should have dialog open', function () {
        controller.yourFunctionWithCallingDialog();

        expect($mdDialog.show).to.have.been.calledOnce;
    });
})

Here is what worked in my case, hope it helps.

`
describe('Unit: mdDialog', function() {

var $mdDialog;

beforeEach(function() {
    angular.mock.module('myApp');

    angular.mock.inject(function($controller, $rootScope, $injector, $compile) {
        controller = $controller;

        $mdDialog = $injector.get('$mdDialog');

        ctrl = controller('capitalStructureController', {
            $scope: scope,
            $element: element
        });
    });
});

it(': Opened', function() {

    var $mdDialogOpened = false;

    $mdDialog.show = jasmine.createSpy().and.callFake(function() {
        $mdDialogOpened = true;
    });

    ctrl.openModal();
    scope.$digest();

    expect($mdDialog.show).to.have.been.calledOnce;
    expect($mdDialogOpened).to.be.true;
});    

});
`

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rtprakash picture rtprakash  路  3Comments

buzybee83 picture buzybee83  路  3Comments

achaussende picture achaussende  路  3Comments

ghost picture ghost  路  3Comments

Dona278 picture Dona278  路  3Comments