How to Mock HTTP Requests in Protractor

Reading Time: 2 minutes

This post is part of a ten-part series on how to write better Protractor tests. You can find the rest of the series here.

Last time we talked about how to add Angular Modules to your Protractor tests. One of the main reasons you’d want to add a module during test time is for HTTP mocking.

Of course, if you can avoid it, you want your Protractor app to test against a real server. The idea is that our tests should be truly end-to-end. But of course, the real world is rarely that simple. You can’t always have your robot Protractor monkeys writing and deleting data in production. So what can we do in that case?

We can mock some or all of our HTTP requests.

Here’s how:

describe('MockingHttp', function() {
  beforeEach(function() {
    browser.addMockModule('httpMocker', function() {
      angular.module('httpMocker', ['ngMockE2E'])
      .run(function($httpBackend) {
            albumId: 1,
            id: 1,
            title: "accusamus beatae ad",
            url: "",
            thumbnailUrl: ""


What we’re doing here is

  1. using addMockModule to add the httpMocker module to our Angular app
  2. using ngMockE2E to give us the functionality to mock our HTTP requests
  3. using run and injecting $httpBackend
  4. using $httpBackend.whenGET to specify that when this particular URL ( is fetched using a GET request, we should instead intercept it and respond with an array with this single, specific object.

Pretty neat right?

Pros: We can mock HTTP requests and specifically control for API responses. We don’t have to worry about our tests failing because the API is down or changed.

Cons: Our end-to-end test is not really end-to-end any longer. Maybe the API changed but we wouldn’t know it because we mocked the result. Also, this only intercepts calls made using the $http service. So if you have a library that is using another HTTP library, it won’t be intercepted using this method.

Learn Protractor in a few hours with our online course

Protractor is a one of the best ways to ensure your app is working correctly because you can write code that acts like a real user. But Protractor can also be confusing and difficult to work with when you're just starting out. We've put together an online course that will help you become a master at Protractor.

You'll save tons of time and frustration learning Protractor because we've worked out everything you need to know. Become a Protractor testing master today!