0

I've got a perfectly working service (a provider, really) that calls a $resource in its $get. Trying to unit test it, I use httpBackend to mockthe response. I inject the service into my test. The resource gets called. I flush() httpBackend, but instead of my success callback getting called, it calls my erro callback with a status of 500, despite the fact that I specified a status of 200. Why is this?

The service:

angular.module('myApp').provider('myData', function() {
    var myData = {empty : true};
    var called = false;
    var success = false;

    var convertDataModel = function(data) {
        // asigns data to properties of myData
    }

    this.$get = ['$resource', function($resource) {
        if (!called && !success) {
            called = true;
            console.log("call resource")
            $resource("/path", {}, {}).get({},
            function(data, status) { // success
                console.log("success!");
                success = true;
                convertDataModel(data);
                myData.empty = false;
            },
            function() { // error
                console.log("error!");
                if (!success) {
                    called = false;
                }
            });
        }
        return myData;
    }];
});

My unit test:

var myData, httpBackend;

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

    inject(function ($httpBackend, _myData_) {
        myData = _myData_;

        httpBackend = $httpBackend;
        $httpBackend.expectGET("/path").respond(200, {facts: true});

    });
});

it("should get and inject the data model", function() {

    expect(myData.empty).toBe(true);
    console.log("flush!");
    httpBackend.flush();
    expect(myData.empty).toBe(false);
    expect(myData.facts).toBe(true);
});

Those last two expects fail, and "error!" is logged. I'm getting a status code of 500, but I have no idea where that is coming from. I specified 200. My error callback does receive the correct data, but the status code has changed. Any idea what could cause that, and how I can fix it?

mcv
  • 4,217
  • 6
  • 34
  • 40
  • There's a good chance the path in the unit test expectation and the path that's actually being used aren't matching correctly. – Vadim Oct 21 '14 at 16:39
  • How do I check? They're both the string "path". – mcv Oct 21 '14 at 16:50
  • Oh wow. I just changed both to "/path", and suddenly my error callback got called. No idea why it didn't call my success callback, though. – mcv Oct 21 '14 at 16:51
  • The error handler should be able to provide the error object. Take a look at it. – Vadim Oct 21 '14 at 16:53
  • I actually do get my data, but with a status code of 500. Weird. – mcv Oct 21 '14 at 16:55

0 Answers0