AngularJS Angle Testing. Httppackend

I have an AngularJS application with unit tests covering it. I added another http request to the .run part of the application that validates user authentication. Now about 60% of my tests fail because they detected an "unexpected HTTP request." Even directive tests fail. How can I avoid running this query in tests? How can I easily mock this query in all tests? I try not to put httpBackend.expect('GET', 'URL')for each test - it works too much.

Jasmine + Karma Testing

Thank. If necessary, I can provide more detailed information.

+4
source share
2 answers

There are several ways to do this:

1.) Include before Tim Castellins suggested, but for each specification file 2.) Include beforeEach in a separate file called app-mocks.js and include in your karma.conf.js (I assume you have) .

karma.conf.js

files: [
    'location/of/app-mocks.js',
    'src/app/**/*.js'
],

application-mocks.js

(function () {
    'use strict';

    beforeEach(inject(function ($httpBackend) {
        $httpBackend.whenGET('blahblahblah.com/cat/:id/food').respond('');
    }));
})();

3.) Separate the user authentication logic from the main application and create the $ http wrapper service ( proposed ). So you can have (simplified example):

app.js

angular.module('myApp', ['myApp.services']);

custom service.js

angular.module('myApp.services', [])
    .factory('User', function ($http) {
        function authenticate() {
            // authenticate user
        }

        return {
            authenticate: authenticate
        };
    });

, .. , unit test , , . , , . , . , , :

beforeEach(module('myApp.services'));

beforeEach(module('myApp.directives'));

.

. , , , .

+2

beforeEach, ,

var httpBackend;
beforeEach(inject(function(_$httpBackend_) {
  httpBackend = _$httpBackend_;
  httpBackend.expect('GET', 'URL').respond('');
}

.respond(''), , . , .

beforeEach jasmine .

0

Source: https://habr.com/ru/post/1544128/


All Articles