Mocking backend with Protractor

364 views Asked by At

I found a lot of similar discussion about this topic but unfortunately none of them fit my scenario. I'm trying to mock the backend response from Protractor for testing a new functionality that is not present in the real API at the moment. I tried different ways for achieving that but with no luck. Every time I run the protractor test, the http request is performed to real API instead of intercepting the request.

Here is my scenario: I have an AngularJS application and there is a search input box in one view like this:

<input type="text" class="form-control rounded input-lg" placeholder="Search Contacts" ng-model="contactCtrl.filter" ng-change="contactCtrl.inspectFilter()" focus="true" id="inputSearch">

Then, I have a controller for that:

  function inspectFilter() {
      $q.all([
        comService.indexContacts($rootScope.$user.cloudContacts, vm.filter)
          .then(function(response) {
            vm.contacts = angular.copy(contacts);
          })
          .catch(function() {
          })
      ]).then(function() {
      });
    }
  }

And the comService.indexContacts that performs the http request:

function indexContacts(url, filter) {
  var filtered_url = filter ? url + '?displayName=' + encodeURIComponent(filter) : url;

  initializeRequest();

  req = {
    headers : {
      'Authorization' : getAuthenticationToken()
    },
    method : 'GET',
    url    : filtered_url
  };

  return $http(req);
}

I'm not going to explain the logic of everything but let's just say that when the user type something in the input filed, the indexContacts function triggers a GET request to the API and the user can see a list of contacts rendered on the screen.

Now I would very like to intercept that $http(req) in my Protractor test and return a mock JSON back but I don't understand how.

'use strict';

describe('Making a call from the contact detail screen', function() {
  beforeAll(function() {
    contacts.goToContacts();
    element(by.id('inputSearch')).clear().sendKeys('gai');
  });

  describe('UAT1 - Clicking the number to make a call', function() {
    it('Given that the user is on the Cloud contact/user detail screen', function() {
      element(by.repeater('contact in contactCtrl.results').row(0)).element(by.css('.tdName')).click();

      dom.waitForElementDisplayed(element(by.css('.contact-modal')));
    });
...
...

Ok, what I do in here is injecting some text into the search field with: element(by.id('inputSearch')).clear().sendKeys('gai'); and this works, but, I want to intercept the http request triggered by the previous comService and, instead, return a mock JSON back to the application to render a custom list of users instead of using the real API for that.

How can I do that????

0

There are 0 answers