Skip to main content

Mock HTTP calls with Angular and Protractor

Mocking Data

One of the benefits using AngularJS is also using some test tools like Protractor. Protractor is a tool that was made for Angular testing. Many times when testing you will need to mock some data so that you can see if your application responds in the correct manner. Let us assume that we have the following HTML file running our application.
<!doctype html>
<html ng-app="demo">
        <script src=""></script>
        <script src=""></script>
        <script src="hello.js"></script>

        <div ng-controller="Hello">
            <p>Hello <span id="gname">{{}}</span></p>
This web application loads a few javascript files from a CDN (content delivery network) and also a "hello.js". In order to get mocking to work we have to make sure that there is a reference to "angular-mocks.js".
Then under "hello.js" we define a simple HTTP request that will get some data and return it in the $scope.exampleResponse variable. This response is exactly what we want to mock.
angular.module('demo', [])
.controller('Hello', function($scope, $http) {
        then(function(response) {
            $scope.exampleResponse =;
Install some basic packages for protractor.
npm install protractor jasmine-core httpbackend
Setup for protractor-conf.js
exports.config = {

    directConnect: true,
    //seleniumAddress: 'http://localhost:4444/wd/hub',

    suites: { "main" : ["spec/**/*.js"]},

    capabilities: {
        "browserName": "chrome"

    baseUrl: "http://localhost:8000/",

    framework: 'jasmine2',

    jasmineNodeOpts: {
        defaultTimeoutInterval: parseInt(process.env.TIMEOUT) || 30000,
        verbose: true,
        realtimeFailure: true,
        //print: function() {}

    resultJsonOutputFile: 'result.json',

    onPrepare: function() {},

    afterLaunch: function(exitCode) {}
The test script, now we can have some fun. The first thing we can do is require httpbackend. There is another way to accomplish mock however httpbackend provides a really simple means of getting the job done. For this example we also create a before and after hook that will allow us to define backend and also clear and teardown the variable.
var HttpBackend = require('httpbackend');
var backend;

describe('A test', function() {
    beforeEach(() => {
        backend = new HttpBackend(browser);

    afterEach(function() {

    it('should diplay Ben as the name', function() {
        backend.whenGET(/exampleResponse/).respond({"name": "Ben"});
If you remember from back in the "hello.js" we did a GET request. "$http.get('http://baseUrl/exampleResponse')" Within the it statement, this is where we can have backend tell Angular that when it needs this GET request send this new data. "backend.whenGET(/exampleResponse/).respond({"name": "Ben"});"
That is all there is too it. For more information and other HTTP handlers like POST, check our the documentation on httpbackend You can also take a look at an example of this work on my github and play with it yourself.


Popular posts from this blog

JSON Schema testing with Postman

Postman is becoming quite the popular tool for accessing and testing REST api services. One of the cool features is that you can write some Javascript tests on your responses. Built into Postman is also the Tiny Validator v4 and Cheerio. Cheerio is a small core JQuery like implementation. The problem I have is that there is no way to import a schema file from a remote place or a file. This will be about how I get around that issue.Pre-request Script var uri=''; $.get(uri + '/someFolder/schema.json', function(schema) { postman.setEnvironmentVariable('schema', JSON.stringify(schema)); }); This Pre-request script is what saves the day. There are a couple of timing issues that are present due to async processing. If you were to put this in your test script your chances of it not completing in time are very high and you would get inconsistent results. If you are familiar with JQuery the $.get should look familiar as a ajax call that d…

Remote API useful tricks for Docker on Mac OS X

Install SocatSocat allow you to forward ports to a variety of things. For Docker forwarding a port to the docker.sock file makes a quick way to get access to the Docker remote api. Docker also allow a way to open up that TCP port however on Mac it is temperamental and hard to usebrew install socat socat -d TCP-LISTEN:2375,reuseaddr,fork UNIX:/var/run/docker.sock & Create an IP aliasRunning Docker containers locally is a fairly common thing. Interconnectivity between containers works naturally. However, sometimes you may also want a container to connect back to the Docker Remote API. If you are constantly on the go changing networks you do not want to have to change that IP address every time. A great use case for this is running Jenkins and using docker slavessudo ifconfig lo0 alias Remote API There are also some interesting endpoints you can use for informationcurl http://localhost:2375 curl http://localhost:2375/containers/json curl http://localhost:2375/image…