question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Protractor Tests without a Backend (or how to mock a backend)

See original GitHub issue

Hi!

I want to write integration tests for an angular app with protractor. As @juliemr mentioned in a comment to a similar issue written by @mrappleton, Protractor is intended for End to End Tests with an actual backend hooked up. This is a reasonable use case and good to know.

However in my case I have a fairly well tested Backend. Therefore I would prefer to have my protractor tests not depend on my backend.

The advantages of this could be

  • Testing the angularjs app can be done in separation of the server
  • I won’t test things twice
  • Less dependencies to worry about

I played around with something similar to @leifhanack backend dsl. It is possible to test the whole App and Mock the Api Routes in the Test. However this feels like a lot of overhead (setup rest server in each test, worry about body parsers,…)

In my App I have a Api Module that talks to the server. I would really like to spy and mock this Api Module from the tests. This is difficult as the tests (protractor) are not executed in the same scope as the app (selenium driven browser).

I would fancy to do something like this in my tests:

Api = $injector.get('Api');
sinon.mock(Api, 'getSomethingFromServer').andRespondWith({foo: 'bar'})
// do tests, go to page, fill out form, submit form, etc...
assert(Api.getSomethingFromServer.wasCalledOnce);

In this case I could test the client in seperation without doing a lot of boilerplate to get up running. I know that this is not possible right now, because $injector is running in the browsers scope.

The only way to do something similar would be to use ptor.addMockModule. This is limited, as it is only possible to replace whole modules (and not mock parts of it) and it is difficult to make assertions on the mocked functions (something like mockedModule.function.wasCalledOnce)

What would be a great way to mock the access to the backend to test an angular app in isolation?

What is the angularjs teams view on this issue?

Issue Analytics

  • State:closed
  • Created 10 years ago
  • Reactions:4
  • Comments:44 (2 by maintainers)

github_iconTop GitHub Comments

4reactions
blabnocommented, Apr 13, 2016

Guys, to you really run all the edge cases with real backend? Mocks are a must!

2016-04-13 11:27 GMT+02:00 Nabil Boag notifications@github.com:

Hey @jonbcampos https://github.com/jonbcampos,

If your goal in testing is to do a full integration test of your stack then mocking the backend is probably counter-productive.

I think a lot of people want to use protractor to acceptance/service test their front end applications in isolation of a back end. My argument though is that real backends are inconstant and inflexible. If you use a real backend, ask yourself the following questions:

  • What happens when my test fails?
  • Was it my application or did the internet connection fail?
  • Was the API team deploying code when I was running my test?
  • What happens if the API is offline or has a version deployed that conflicts with my application?

If your application makes very few API calls or the UX doesn’t change based on different API responses then Angular’s built-in ngMock mocking tools are great.

However, as applications grow in size and complexity, integration tests become increasingly flakey (non-deterministic). Mocks allow you to control the test process carefully, but it can become difficult to manage API response mocks, change scenarios and test complex UX interactions (which is what people like @germanio https://github.com/germanio are experiencing).

— You are receiving this because you are subscribed to this thread. Reply to this email directly or view it on GitHub https://github.com/angular/protractor/issues/125#issuecomment-209332232

4reactions
wakandancommented, Sep 30, 2013

I think I’m doing something similar to what you’re wanting to setup, don’t remember where I read about it but here are the steps:

I have a mocked backend module mocked-backend.js with

exports.httpBackendMock = function() {
    angular.module('httpBackendMock', ['mainApp', 'ngMockE2E'])
    .run(function($httpBackend) {
        console.log('Test platform bootstrapping');  
        ...     
        $httpBackend.whenGET('/events').respond([sampleEvent]);        
        $httpBackend.whenGET('/events/' + sampleEventId).respond(sampleEvent);
        $httpBackend.whenGET('/login').passThrough();
        $httpBackend.whenGET(/partials\/.*/).passThrough();        
        $httpBackend.whenPOST('/events').respond(function(method, url, data) {
            data._id = 123456789;
            return [200, angular.toJson(data), {}];
        });
        $httpBackend.whenDELETE('/events/' + sampleEventId).respond(function(method, url, data) {
            return [200, {
                delete: sampleEvent
            }, {}];
        });
        console.log('Test platform bootstrapping ... done');
    });
}

where the mainApp is name of the real apps, in which all the routes are declared. Notice the dependency to ngMockE2E, you will need to have reference to angular-mocks.js in your index.html file for this to work.

In my protractor scenario file:

var mockModule = require('./mocked-backend');

And in your test in your beforeEach block you could put

beforeEach(function() {
     ptor.addMockModule('httpBackendMock', mockModule.httpBackendMock);        
});

The only I couldn’t figure out was setting response header with Set-Cookies so that the cookie part of my app could be tested. I would like to hear some insight about it as well.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Protractor, mocking backend with angular2 on api request
As there is no support for mocked modules in angular 2, i made a small protractor plugin that allows mock ajax request.
Read more >
Mocking and Stubbing with protractor - Intellipaat Community
I want to test my angular app with a protractor. The app has an API Module that talks to the server During these...
Read more >
Protractor Tests without a Backend (or how to mock a backend ...
Protractor Tests without a Backend (or how to mock a backend ... Popularity. 138 views; 0 downloads. Clipart details. 1.52 KB; File type:...
Read more >
Mock back-end for UI testing (Angular) - DEV Community ‍ ‍
This post describes how to integrate Angular and WireMock (a mock HTTP back-end server). Protractor, along side Jasmine is used to create ...
Read more >
Lesson 15: Creating a Mock Backend - Elite Ionic
WARNING: This module is deprecated and no longer receives updates. Protractor is likely being removed as the default from Angular applications and Protractor...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found