Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
582 views
in Technique[技术] by (71.8m points)

testing - 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();
  });

});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...