Skip to content
This repository has been archived by the owner on Aug 29, 2023. It is now read-only.

How to Unit test controller containing $mdDialog? #1482

Closed
mick26 opened this issue Feb 12, 2015 · 4 comments
Closed

How to Unit test controller containing $mdDialog? #1482

mick26 opened this issue Feb 12, 2015 · 4 comments

Comments

@mick26
Copy link

mick26 commented Feb 12, 2015

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

@ThomasBurleson
Copy link
Contributor

Please post this in the Angular Material Forum

@dmackerman
Copy link

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

@patrykbialek
Copy link

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

@eikishi01
Copy link

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

});
`

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants