Trouble Using AngularJS $httpBackend to respond to BreezeJS executeQuery

968 Views Asked by At

Has anyone been able to build specs or e2e tests using $httpBackend while having BreezeJS function as your entity manager?

Here is the BreezeJS code:

function getClientsAll() {
    var query = breeze.EntityQuery.from('clients').using($clientJsonResultsAdapter);        
    return em.executeQuery(query);
}

And here is the test code from the Jasmine Spec using AngularJS $httpBackend:

it('should show all clients', function() {
    $httpBackend.expectGET(/clients/).respond([ 200, mockData.clients.GET]);
    backupModelService.getClientsAll()
        .then(function() {
            console.log("getClientsAll success");
        })
        .fail(function() {
            console.log("getClientsAll fail");
        })
    $httpBackend.flush();//error thrown here
});

But I get the jasmine test failure

Error: No pending request to flush !

This breeze method works fine running in the browser but not during tests. However, if I convert to using angularJS $http or $resource, this test will pass. I'm wondering if BreezeJS is not compatible with the $httpBackend for spec and e2e testing.

Thanks for any insight.

//EDIT --- AFTER TRYING TO MOCK AJAX BECAUSE OF STEVE'S RESPONSE

This fails as well.

    var success = jasmine.createSpy('success');
    var fail = jasmine.createSpy('fail');
    spyOn($, 'ajax').andCallFake(function (req) {
        var d = $.Deferred();
        d.resolve(mockData.clients.GET);
        return d.promise();
    });
    backupModelService.getClientsAll()
        .then(success)
        .fail(fail);

    expect(success).toHaveBeenCalled();
2

There are 2 best solutions below

1
On

Breeze does not use Angular's $http or $resource for sending XHR. It uses jQuery's AJAX implementation. So queries performed using em.executeQuery(query) will not go through $httpBackend.

When testing using Breeze, you should spy/stub/mock jQuery's $.ajax, as described in this post.

0
On

That's not fully true. Breeze added an ajax adapter for $http in v.1.4.4 This is the way to setup the ajax adapter

function configBreeze($q, $http) {
    // tell the adapter to use your app module's $http for ajax calls

    var ajax = breeze.config.initializeAdapterInstance('ajax', 'angular');
    ajax.setHttp($http);
}

After this you will be able to use $httpBackend on your tests

More info here http://www.breezejs.com/documentation/customizing-ajax and here Breeze using angular $http interceptor