1

I am having a bit of trouble testing a HTTP POST in AngularJs with Jasmine.

I have a controller that looks like so:-

appControllers.controller("TaskAddController", function ($scope, $http) {
    $scope.task = {};
    $scope.messages = {};

    $scope.actions = {
        save : function() {
            $http.post("/ajax/tasks/save", $scope.task)
            .then(function() {
                $scope.messages.success = true;
                $scope.task = {};
            });
        }
    };
});

I am testing it like so:-

describe("TaskAddController", function() {
    var createController, scope, $httpBackend;

    beforeEach(function () {
        module('appControllers');

        scope = {};

        inject(function ($injector) {
            $httpBackend = $injector.get("$httpBackend");
        });

        inject(function ($controller) {
            createController = function () {
                return $controller("TaskAddController", { $scope: scope });
            };
        });
    });

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

    it("when actions.save is called then should call service", function () {
        var task = {
            title: "Title",
            description: "Description"
        };

        $httpBackend.expectPOST("/ajax/tasks/save", task);
        createController();
        scope.task = task;
        scope.actions.save();
        $httpBackend.flush();
    });
});

This causes me to get the following error Error: No pending request to flush !

What am I doing wrong?

Thanks.

1 Answer 1

3

What version of AngularJS are you using?

When I run the code I get: Error: No response defined !

When I add a response the test passes:

$httpBackend.expectPOST("/ajax/tasks/save", task).respond({});
Sign up to request clarification or add additional context in comments.

1 Comment

perfect thanks. I can't believe I missed that. Serves me right for trying to do things late at night!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.