Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock an AJAX request?

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

<!doctype html>
<html lang="en" ng-app="myApp">
<head>
  <meta charset="utf-8">
  <title>My Test AngularJS App</title>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular-resource.min.js"></script>

  <script language="javascript" type="text/javascript">
      angular.module('myApp', ['ngResource']);
      function PlayerController($scope,$resource){
        $scope.player = $resource('player.json').get();
      }
    </script>

</head>
  <body ng-controller="PlayerController">
    <p>Hello {{player.name}}</p>
  </body>
</html>

Player gets correctly fetched from a file named player.json on the server and the following test passes. How do I pass different json in to this test and prevent the fetch back to the server?

/*
How do I pass in
player.json -> {"name":"Chris"}
*/
describe('my app', function() {

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

  it('should load player from player.json', function() {
    expect(element('p:first').text()).
        toMatch("Hello Chris");
    pause();
  });

});
like image 318
Chris Avatar asked Dec 16 '12 06:12

Chris


1 Answers

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

like image 168
Caio Cunha Avatar answered Oct 30 '22 12:10

Caio Cunha