(function() {
'use strict';
angular.module('MyApp', []);
angular.module('MyApp')
.constant("ROUTES", {
get: "real-get-path"
});
angular.module('MyApp')
.factory('MyFactory', ['$http', '$timeout', 'ROUTES', MyFactory]);
function MyFactory($http, $timeout, ROUTES) {
return {
myGet: function(id) {
var random = Math.random() * 1000;
return $timeout(function () {
return $http.get(ROUTES.get, {
params: { id: id }
})
.then(function(response) {
return response.data;
});
}, random);
}
};
}
})();
<!DOCTYPE html>
<html ng-app="MyApp">
<head>
<meta charset="utf-8" />
<title>Jasmine test</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.5.2/jasmine.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.5.2/jasmine-html.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.5.2/boot.js"></script>
<script src="https://code.jquery.com/jquery-2.0.3.min.js"></script>
<script src="https://code.angularjs.org/1.5.8/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular-mocks.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.5.2/jasmine.min.css" />
<!-- The application code -->
<script src="app.js"></script>
<!-- The test specs -->
<script src="app.spec.js"></script>
</head>
<body>
<div id="HTMLReporter" class="jasmine_reporter"></div>
</body>
</html>
// suggested by: http://stackoverflow.com/a/40155728/4784342
describe('simple directive', function() {
var $http, $timeout, scope, MyFactory, $httpBackend;
var ROUTES = {
get: 'mocked-get-path'
};
beforeEach(module('MyApp', function ($provide) {
$provide.constant('ROUTES', ROUTES);
}));
beforeEach(module('MyApp'));
beforeEach(inject(function(_$rootScope_, _$http_, _$timeout_, _MyFactory_, _$httpBackend_) {
$httpBackend = _$httpBackend_;
scope = _$rootScope_.$new();
$http = _$http_;
$timeout = _$timeout_;
MyFactory = _MyFactory_;
}));
it('should use ROUTES.get on method myGet', function(done) {
spyOn(Math, "random").and.returnValue(0.01);
spyOn($http, "get").and.callThrough();
MyFactory.myGet('elem1')
.then(function(res) {
expect($http.get).toHaveBeenCalledWith(ROUTES.get, {params: {id: 'elem1'}});
done();
});
$httpBackend
.when('GET', "mocked-get-path?id=elem1")
.respond(200, { foo: 'bar' });
$timeout.flush(100);
$timeout.verifyNoPendingTasks();
$httpBackend.flush();
});
});