How to mock an AJAX request?

后端 未结 3 1777
-上瘾入骨i
-上瘾入骨i 2020-12-16 05:57

What is the simplest way to modify scenarios.js to mock an AJAX request during an end-to-end test?




        
相关标签:
3条回答
  • 2020-12-16 06:09

    You should use $httpBackend from ngMockE2E module to mock http requests. Take a look at the docs.

    0 讨论(0)
  • 2020-12-16 06:19

    It appears that currently you can not ONLY modify scenarios.js to include $httpBackend mocking. You will have to add some other code to support it.

    For me the best way seems to be the following

    Add a myAppTest.js in your test folder that includes 'ngMockE2E' so you don't need to pollute your existing app.js

    'use strict';
    
    angular.module('myAppTest', ['myApp', 'ngMockE2E'])
    .run(function($httpBackend) {
        var user = {name: 'Sandra'};
        $httpBackend.whenGET('/api/user').respond(user); 
    });
    

    Then add a separate test-index.html that uses the new myAppTest.js. Note you need to include angular-mocks.js. (This leaves your production html file intact and free of mocks)

    <!doctype html>
    <html lang="en" ng-app="myAppTest">
    <head>
      <script src="lib/angular/angular.js"></script>
      <script src="lib/angular/angular-resource.js"></script>
      <script src="../test/lib/angular/angular-mocks.js"></script>
      <script src="js/app.js"></script>
      <script src="js/controllers.js"></script>
      <script src="../test/e2e/myAppTest.js"></script>
    </head>
    <body>
      <div ng-view></div>
    </body>
    </html>
    

    Then in your scenarios.js just reference your new test-index.html before running the other tests.

    beforeEach(function() {
       browser().navigateTo('../../app/test-index.html#/');
    });
    

    I've adapted this example from:

    https://github.com/stephennancekivell/angular_e2e_http/tree/ngMockE2E

    0 讨论(0)
  • 2020-12-16 06:29

    As a start, add angular-mocks.js and the file (app.js for example) where you will create the module to your index.html page that contains the ng-app declaration.

    <html lang="en" ng-app="myApp">
      <head>
        <script src="js/app.js"></script>
        <script src="../test/lib/angular/angular-mocks.js"></script>
        ...
    

    Then in the app.js file define the module and add the mock responses.

    var myAppDev = angular.module('myApp', ['ngResource','ngMockE2E']);
    
    myAppDev.run(function($httpBackend) {
        var user = {name: 'Sandra'};
        $httpBackend.whenGET('/api/user').respond(user); 
    });
    
    0 讨论(0)
提交回复
热议问题