material icon indicating copy to clipboard operation
material copied to clipboard

How to Unit test controller containing $mdDialog?

Open mick26 opened this issue 11 years ago • 4 comments

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

mick26 avatar Feb 12 '15 11:02 mick26

Please post this in the Angular Material Forum

ThomasBurleson avatar Feb 12 '15 15:02 ThomasBurleson

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

dmackerman avatar Feb 13 '15 20:02 dmackerman

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;
    });
})

patrykbialek avatar Sep 12 '15 21:09 patrykbialek

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;
});    

}); `

eikishi01 avatar Oct 19 '16 15:10 eikishi01