reutsey
reutsey

Reputation: 1993

Updating mocked objects in protractor tests

Just wondering if anyone has a good solution for updating mocked calls within a protractor test. I need to be able to mock a call (which I can do using ngMockE2E) but the next time the call is made, I want it to come back with different results.

httpbackend.when('GET', ....URL....).respond(200, results);

where results is a json object that is returned.

The first time the call is made it is coming back with the correct json. But within the same test, I want to update those results so that the next time the call is made, it returns the updated json.

Thoughts?

Upvotes: 1

Views: 269

Answers (1)

Michael Radionov
Michael Radionov

Reputation: 13319

When using http-backend-proxy module, it is possible to modify a response for a request with the same URL with the help of context object. To do that, you have pass a function to the .respond() method, which must return an array with a status and response data. Inside this function you have access to a so called context object, which is used to transfer data from Protractor test to an Angular app on a page. It is possible to modify this context object from within a test, so Angular app could receive another response.

var HttpBackend = require('http-backend-proxy');
var proxy = new HttpBackend(browser);

// ...

// use one data for first response
proxy.context = {
    notes: notifications,
    messages: allMessages
};

proxy.when('GET', '...notificationsURL...').respond(function () {
    return [200, $httpBackend.context];
});

// here make a first call

// use another data for second response
proxy.context = {
    notes: notifications2,
    messages: allMessages2
};

proxy.syncContext(); // required, update context content for Angular app

// here make a second call

Note: the function you pass to .respond() will be serialized (converted to string) and injected on a page, by default to access a context object from Angular a variable $httpBackend is used. Take a look at this docs section to rename it - Configuring the Context Object.

Upvotes: 1

Related Questions