YourReflection YourReflection - 8 months ago 32
AngularJS Question

Jasmine: How to test if the correct URL has been called in a GET request

I have a service whose function I'd like to test. However, I have no idea on how to mock a service function that is used inside each function in that service. I want to check, if the correct URL is called.

Here is my service:

angular.module("myModule").service('myService', MyService);

MyService.$inject = ['$http'];

function MyService($http) {
var myService = this;

myService.request = function (reqType, url, headers, requestBody, fnc, fncFail) {
$http(createRequest(reqType, point, headers, requestBody)).then(function (response) {
if (typeof fnc == 'function') {
}, function (response) {
if (typeof fncFail == 'function') {

myService.getInfo = function (id, fnc, fncFail) {
myService.request("GET", "myURL", {"Accept":"application/json"}, null, function (data) {
}, fncFail);

Now a snippet of my test suite:

beforeEach(inject(function ($injector) {
service = $injector.get("myService");
httpBackend = $injector.get("$httpBackend");
http = $injector.get("$http");

it("function getInfo is called with the correct URL", function () {
spyOn(http, 'get').and.callThrough();
myService.getInfo(id, fnc, fncFail);

I am not sure, if this is the correct approach to testing my method "getInfo" because it calls the other service function ("request").


Use $httpBackend to expect XHR calls. With the following afterEach block the test will fail if the call is not made.

afterEach(function() {

it("function getInfo is called with the correct URL", function () {
    httpBackend.expect('GET', "myurl").respond(200, {mocked: "response"});
    myService.getInfo(id, fnc, fncFail);