GamerDev
GamerDev

Reputation: 2016

jasmine error $httpBackend Unexpected request without domain

My jasmine test for $httpBackend won't work unless I add the domain name, i.e. http://localhost:9808/

Since this test is used in several different environments I cannot use http://localhost:9808/

Without the domain I get this error:

Uncaught Error: Unexpected request: GET http://localhost:9808/api/mymethod No more request expected

    describe('test my service', function () {
        'use strict';

        var $httpBackend,
          myService;

        beforeEach(inject(function (_$injector_, _$httpBackend_) {
            var $injector = _$injector_;
            $httpBackend = _$httpBackend_;

            myService = $injector.get('myService');

            // this works
            //$httpBackend.whenGET('http://localhost:9808/api/mymethod').respond(200, mockData);

            // this throws error
            $httpBackend.whenGET('/api/mymethod').respond(200, mockData);
        }));

    afterEach(function () {
            $httpBackend.verifyNoOutstandingExpectation();
            $httpBackend.verifyNoOutstandingRequest();
        }); 

        it('check service exists and has methods', function () {
            expect(myService).toBeDefined();
            expect(myService.somemethod).toBeDefined();

        $httpBackend.flush();
    });
}); 

I even tried adding these lines to the beforeEach

// this also throws error

$httpBackend.when('GET', '/api/mymethod').respond(200, mockData);

// even adding expect still throws the error in the beforeEach $httpBackend.expectGET('/api/mymethod');

Any ideas or suggestions on how to get this to work without using the domain?

Here is the service code that actually makes the request:

(function(app) {

    'use strict';
    function MyService(apiService) {
        var returnDataObject = [];

        apiService.getAll().then(function(result) {
            returnDataObject = result.data;
        });

        this.myMethod = function() {
            if(returnDataObject) {
             return returnDataObject;
            }
            else {
            return null;
            }
        };

    }

    app.service('MyService', MyService);
    MyService.$inject = ['APIService'];

})(angular.module('app.mymodule'));

Upvotes: 1

Views: 218

Answers (2)

GamerDev
GamerDev

Reputation: 2016

Ok, after seeing this post https://stackoverflow.com/questions/29809436/cannot-inject-providers-into-karma-test

I was able to resolve my problem by adding the beforeEach below to my spec file. I am using angular v1.5.4 and angular-ui-router v0.2.18

beforeEach(module(function($urlRouterProvider) {
        $urlRouterProvider.deferIntercept();
    }));

Upvotes: 0

Pedro Vaz
Pedro Vaz

Reputation: 820

I guess you could use a regex to match the URL

You could do:

var method = 'GET';
var url = '/mymethod';
$httpBackend.when(method, new RegExp('\\' + url)).respond(200, mockData);

Upvotes: 0

Related Questions