mock $httpBackend in angular e2e tests

前端 未结 3 734
终归单人心
终归单人心 2020-12-30 12:16

Does anyone have an idea how to mock $httpBackend in angular e2e tests? The idea is stubbing XHR requests while running tests on travis-ci. I\'m using karma to proxy assets

相关标签:
3条回答
  • 2020-12-30 12:39

    If you are really trying to mock out the backend in a E2E test (these tests are called Scenarios, while Specs are used for unit testing) then this is what I did in a project I was working on earlier.

    The application I was testing was called studentsApp. It was an application to search for students by querying a REST api. I wanted to test the application without actually querying that api.

    I created a E2E application called studentsAppDev that I inject studentsApp and ngMockE2E into. There I define what calls the mockBackend should expect and what data to return. The following is an example of my studentsAppDev file:

    "use strict";
    
    // This application is to mock out the backend. 
    var studentsAppDev = angular.module('studentsAppDev', ['studentsApp', 'ngMockE2E']);
    studentsAppDev.run(function ($httpBackend) {
    
        // Allow all calls not to the API to pass through normally
        $httpBackend.whenGET('students/index.html').passThrough();
    
        var baseApiUrl = 'http://localhost:19357/api/v1/';
        var axelStudent = {
            Education: [{...}],
            Person: {...}
        };
        var femaleStudent = {
            Education: [{...}],
            Person: {...}
        };
        $httpBackend.whenGET(baseApiUrl + 'students/?searchString=axe&')
            .respond([axelStudent, femaleStudent]);
        $httpBackend.whenGET(baseApiUrl + 'students/?searchString=axel&')    
            .respond([axelStudent, femaleStudent]);
        $httpBackend.whenGET(baseApiUrl + 'students/?searchString=axe&department=1&')
            .respond([axelStudent]);
        $httpBackend.whenGET(baseApiUrl + 'students/?searchString=axe&department=2&')
            .respond([femaleStudent]);
        $httpBackend.whenGET(baseApiUrl + 'students/?searchString=axe&department=3&')    
            .respond([]);
    
        ...
    
        $httpBackend.whenGET(baseApiUrl + 'departments/?teachingOnly=true')
            .respond([...]);
        $httpBackend.whenGET(baseApiUrl + 'majors?organization=RU').respond([...]);
    });
    

    Then, I have a first step in my Jenkins CI server to replace the studentsApp with studentsAppDev and add a reference to angular-mocks.js in the main index.html file.

    0 讨论(0)
  • 2020-12-30 12:44

    This feels more like unit/spec testing. Generally speaking you should use mocks within unit/spec tests rather than e2e/integration tests. Basically, think of e2e tests as asserting expectations on a mostly integrated app...mocking out things kind of defeats the purpose of e2e testing. In fact, I'm not sure how karam would insert angular-mocks.js into the running app.

    The spec test could look something like...

    describe('Controller: MainCtrl', function () {
        'use strict';
    
        beforeEach(module('App.main-ctrl'));
    
        var MainCtrl,
            scope,
            $httpBackend;
    
        beforeEach(inject(function ($controller, $rootScope, $injector) {
            $httpBackend = $injector.get('$httpBackend');
            $httpBackend.when('GET', '/search/mow').respond([
                {}
            ]);
            scope = $rootScope.$new();
            MainCtrl = $controller('MainCtrl', {
                $scope: scope
            });
        }));
    
        afterEach(function () {
            $httpBackend.verifyNoOutstandingExpectation();
            $httpBackend.verifyNoOutstandingRequest();
        });
    
        it('should search for mow', function () {
            scope.search = 'mow';
            $httpBackend.flush();
            expect(scope.accounts.length).toBe(1);
        });
    });
    
    0 讨论(0)
  • 2020-12-30 12:46

    Mocking out your backend is an important step in building a complex Angular application. It allows testing to be done without access to the backend, you don't test things twice and there are less dependencies to worry about.

    Angular Multimocks is a simple way to test how your app behaves with different responses from an API.

    It allows you to define sets of mock API responses for different scenarios as JSON files.

    It also allows you to change scenarios easily. It does this by allowing you to compose “scenarios” out of different mock files.

    How to add it to your app

    After adding the required files into your page, simply add scenario as a dependency to your application:

    angular
      .module('yourAppNameHere', ['scenario'])
      // Your existing code here...
    

    Once you have added this to your app you can start to create mocks for API calls.

    Lets say your app makes the following API call:

    $http.get('/games').then(function (response) {
      $scope.games = response.data.games;
    });
    

    You can create a default mock file:

    Example of someGames.json

    {
      "httpMethod": "GET",
      "statusCode": 200,
      "uri": "/games",
      "response": {
        "games": [{"name": "Legend of Zelda"}]
      }
    }
    

    When you load your application, calls to /games will return 200 and {"games": [{"name": "Legend of Zelda"}]}

    Now lets say you want to return a different response for the same API call, you can place the application in a different scenario by changing the URL e.g. ?scenario=no-games

    The no-games scenario can use a different mock file, lets say one like this:

    Example of noGames.json

    {
      "httpMethod": "GET",
      "statusCode": 200,
      "uri": "/games",
      "response": {
        "games": []
      }
    }
    

    Now when you load your application, calls to /games will return 200 and {"games": []}

    Scenarios are composed of various JSON mocks in a manifest like this:

    {
      "_default": [
        "games/someGames.json"
      ],
      "no-games": [
        "games/noGames.json"
      ]
    }
    

    You can then exclude the mock files and strip the scenario dependency in your production app.

    0 讨论(0)
提交回复
热议问题