0

I'm applying some tests in an existing AngularJS application in order to ensure it's correct behaviour for future changes in the code.

I am pretty new with Jasmine & Karma testing, so I've decided to start with a small and basic service which performs an http request to the backend, and waits for the result with a promise, nothing new.

Here's the service method to test:

function getInformedConsent(queryParameters) {
    var def = $q.defer(),
        httpParameters = {
            url: ENV.apiEndpoint + '/urlResource',
            method: 'GET',
            params: queryParameters,
            paramSerializer: '$httpParamSerializerJQLike'
        };

    $http(httpParameters)
        .then(
            function (response) {
                def.resolve(response);
            },
            function (error) {
                def.reject(error);
            }
        );

    return def.promise;
}

And here my test:

it('getInformedConsent method test', function() {
    $httpBackend.expectGET(/.*\/urlResource?.*/g)
        .respond(informedConsentJson.response);

    var promise;

    promise = InformedconsentService.getInformedConsent(informedConsentJson.queryParameters[0]);
    promise
        .then(function(response) {
            console.log(response);
            expect(response).toEqual(informedConsentJson.response);
        });

    $httpBackend.flush();

});

informedConsentJson as you can supose, is a fixture with input and the expected output.

Reading AngularJS documentation, I decided to use $httpBackend, because it's already a mock of $http service, so I thought it could be useful.

The problem is that somewhere in the code, someone is broadcasting a "$locationChangeStart" event and executing

$rootScope.$on('$locationChangeStart', function (event,current,old) {
    /* some code here */
});

in app.js.

I'm not trying to change the URL, i'm just trying to get some data from the mocked backend.

I asume that is because I'm not using $http mock ($httpBackend) as it should be used.

Anyone can help me with $http with configuration JSON mock? It's freaking me out.

Thank you all in advance for your time and your responses

marc
  • 527
  • 6
  • 23
  • 1
    Side note: on your `getInformedConsent`, you can simply `return $http(httpParameters)` instead of using a deferred that just wraps the original promise. [$q.defer: You're doing it wrong](http://www.codelord.net/2015/09/24/$q-dot-defer-youre-doing-it-wrong/) – Leonardo Chaia Feb 16 '17 at 15:48
  • 1
    @LeonardoChaia very interesting post. Thank you!! – marc Feb 16 '17 at 15:55
  • Hey @wrrzag, no problem. Maybe you can edit your question to explain the actual issue you're having. – Leonardo Chaia Feb 16 '17 at 15:59
  • @LeonardoChaia done. Hope the changes will be useful to understand the problem. – marc Feb 16 '17 at 16:17

0 Answers0