Skip to content

Instantly share code, notes, and snippets.

@teone
Last active April 17, 2020 19:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teone/9238e8674e86512c95dbc01c2c0d01f7 to your computer and use it in GitHub Desktop.
Save teone/9238e8674e86512c95dbc01c2c0d01f7 to your computer and use it in GitHub Desktop.
Mocking promises in Angular Karma/Jasmine tests
(function () {
'use strict';
describe('The service', () => {
let service, scope;
const resolveValue = 'The value you want to resolve.';
const mock = {
promise: () => {
return {
then: cb => cb(resolveValue)
}
}
};
// load the application module and provide the mock
beforeEach(module('myModule', ($provide) => {
$provide.value('myMock', mock);
}));
// inject the service
beforeEach(inject(function (_myService_, $rootScope) {
service = _myService_;
scope = $rootScope;
// spy on the promise
spyOn(mock, 'promise').and.callThrough();
}));
describe('when permission are not granted', () => {
it('should request permission', () => {
service.doSomething();
expect(mock.promise).toHaveBeenCalled();
scope.$apply(); // this resolve the promise
expect(something).to...
});
});
});
})();
(function () {
'use strict';
describe('The service', () => {
let service, scope, mock, deferred;
// load the application module and provide the mock
beforeEach(module('myModule', ($provide) => {
$provide.value('myMock', mock);
}));
// inject the service
beforeEach(inject(function (_myService_, $rootScope, $q) {
service = _myService_;
scope = $rootScope;
// create the promise
mock = {
promise: jasmine.createSpy('query').and.callFake(function(){
return deferred.promise;
});
};
}));
describe('when permission are not granted', () => {
it('should request permission', () => {
service.doSomething();
expect(mock.promise).toHaveBeenCalled();
scope.$apply(); // this resolve the promise
expect(something).to...
});
});
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment