Last active
April 17, 2020 19:44
-
-
Save teone/9238e8674e86512c95dbc01c2c0d01f7 to your computer and use it in GitHub Desktop.
Mocking promises in Angular Karma/Jasmine tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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... | |
}); | |
}); | |
}); | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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