I am unit testing an Angular controller with karma/Jasmine. The controller contains the $mdDialog service. How do I mock out $mdDialog?
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;
});
});
`
Most helpful comment