S
S
semolex2015-07-09 10:58:45
Angular
semolex, 2015-07-09 10:58:45

How to properly test HTTP request in Karma \ AngularJS?

Hello!
I have the following problem:
I need to test the controller on AngularJS using the Karma framework. Everything is fine until the moment when you need to test a function that changes one field in the database. Everything works, but when I run the test - the result is very unexpected, it seems that nothing works :).
Here is the code:

// Готовим пре-реквизиты.
    beforeEach(inject(function($controller, $rootScope, _$httpBackend_, $filter) {
        scope = $rootScope.$new();
        $httpBackend = _$httpBackend_;
        booksPriceUpdated = $httpBackend.whenPOST('http://localhost:8000/v1/books/d2f38d822941c1e7b90f71296a9ac453').respond(EXPEXTED_UPDATE_RESULT);
        createController = function() {
            return $controller('BooksCtrl', {
                $scope: scope
            });
        };
    }));
// Собственно, проблемная часть.
    it('should test updatePrice function', function() {
        createController();
        $httpBackend.flush();
        expect(scope.books[0].price).toBe(0); // pre-loaded priority
        scope.updatePrice(scope.books[0], {
            "price": 1,
        });
        $httpBackend.flush();
        expect(scope.books[0].price).toEqual(1); // FAIL, ВСЕРАВНО ВОЗВРАЩАЕТ 0!
    });

// Вот функция в контроллере:

            $scope.updatePrice = function(data) {
                bibleApi.post('/books/' + data.id, {

                    "price": data.price

                }).success(function(data, status, headers, config) {
                    console.log('Sucessfully updated price: ' + data.name + ', price: ' + data.price)
                }).
                error(function(data, status, headers, config) {
                    console.log(data.message)
                });
            };

Everything works fine when you just run the application. You need to change the field, everything is fine. I can't figure out what I'm doing wrong. I will be grateful for help. Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
_
_ _, 2015-07-09
@AMar4enko

Tell me, where does $scope.updatePrice change the data in your scope?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question