direktori cari
AngularJS API Reference auto auto/service auto/service/$injector auto/service/$provide ng ng/directive ng/directive/a ng/directive/form ng/directive/input ng/directive/input[checkbox] ng/directive/input[date] ng/directive/input[dateTimeLocal] ng/directive/input[email] ng/directive/input[month] ng/directive/input[number] ng/directive/input[radio] ng/directive/input[text] ng/directive/input[time] ng/directive/input[url] ng/directive/input[week] ng/directive/ngApp ng/directive/ngBind ng/directive/ngBindHtml ng/directive/ngBindTemplate ng/directive/ngBlur ng/directive/ngChange ng/directive/ngChecked ng/directive/ngClass ng/directive/ngClassEven ng/directive/ngClassOdd ng/directive/ngClick ng/directive/ngCloak ng/directive/ngController ng/directive/ngCopy ng/directive/ngCsp ng/directive/ngCut ng/directive/ngDblclick ng/directive/ngDisabled ng/directive/ngFocus ng/directive/ngForm ng/directive/ngHide ng/directive/ngHref ng/directive/ngIf ng/directive/ngInclude ng/directive/ngInit ng/directive/ngKeydown ng/directive/ngKeypress ng/directive/ngKeyup ng/directive/ngList ng/directive/ngModel ng/directive/ngModelOptions ng/directive/ngMousedown ng/directive/ngMouseenter ng/directive/ngMouseleave ng/directive/ngMousemove ng/directive/ngMouseover ng/directive/ngMouseup ng/directive/ngNonBindable ng/directive/ngOpen ng/directive/ngPaste ng/directive/ngPluralize ng/directive/ngReadonly ng/directive/ngRepeat ng/directive/ngSelected ng/directive/ngShow ng/directive/ngSrc ng/directive/ngSrcset ng/directive/ngStyle ng/directive/ngSubmit ng/directive/ngSwitch ng/directive/ngTransclude ng/directive/ngValue ng/directive/script ng/directive/select ng/directive/textarea ng/filter ng/filter/currency ng/filter/date ng/filter/filter ng/filter/json ng/filter/limitTo ng/filter/lowercase ng/filter/number ng/filter/orderBy ng/filter/uppercase ng/function ng/function/angular.bind ng/function/angular.bootstrap ng/function/angular.copy ng/function/angular.element ng/function/angular.equals ng/function/angular.extend ng/function/angular.forEach ng/function/angular.fromJson ng/function/angular.identity ng/function/angular.injector ng/function/angular.isArray ng/function/angular.isDate ng/function/angular.isDefined ng/function/angular.isElement ng/function/angular.isFunction ng/function/angular.isNumber ng/function/angular.isObject ng/function/angular.isString ng/function/angular.isUndefined ng/function/angular.lowercase ng/function/angular.module ng/function/angular.noop ng/function/angular.toJson ng/function/angular.uppercase ng/object ng/object/angular.version ng/provider ng/provider/$animateProvider ng/provider/$compileProvider ng/provider/$controllerProvider ng/provider/$filterProvider ng/provider/$httpProvider ng/provider/$interpolateProvider ng/provider/$locationProvider ng/provider/$logProvider ng/provider/$parseProvider ng/provider/$rootScopeProvider ng/provider/$sceDelegateProvider ng/provider/$sceProvider ng/service ng/service/$anchorScroll ng/service/$animate ng/service/$cacheFactory ng/service/$compile ng/service/$controller ng/service/$document ng/service/$exceptionHandler ng/service/$filter ng/service/$http ng/service/$httpBackend ng/service/$interpolate ng/service/$interval ng/service/$locale ng/service/$location ng/service/$log ng/service/$parse ng/service/$q ng/service/$rootElement ng/service/$rootScope ng/service/$sce ng/service/$sceDelegate ng/service/$templateCache ng/service/$timeout ng/service/$window ng/type ng/type/$cacheFactory.Cache ng/type/$compile.directive.Attributes ng/type/$rootScope.Scope ng/type/angular.Module ng/type/form.FormController ng/type/ngModel.NgModelController ngAnimate ngAnimate/provider ngAnimate/provider/$animateProvider ngAnimate/service ngAnimate/service/$animate ngCookies ngCookies/service ngCookies/service/$cookies ngCookies/service/$cookieStore ngMessages ngMessages/directive ngMessages/directive/ngMessage ngMessages/directive/ngMessages ngMock ngMock/function ngMock/function/angular.mock.dump ngMock/function/angular.mock.inject ngMock/function/angular.mock.module ngMock/object ngMock/object/angular.mock ngMock/provider ngMock/provider/$exceptionHandlerProvider ngMock/service ngMock/service/$exceptionHandler ngMock/service/$httpBackend ngMock/service/$interval ngMock/service/$log ngMock/service/$timeout ngMock/type ngMock/type/angular.mock.TzDate ngMockE2E ngMockE2E/service ngMockE2E/service/$httpBackend ngResource ngResource/service ngResource/service/$resource ngRoute ngRoute/directive ngRoute/directive/ngView ngRoute/provider ngRoute/provider/$routeProvider ngRoute/service ngRoute/service/$route ngRoute/service/$routeParams ngSanitize ngSanitize/filter ngSanitize/filter/linky ngSanitize/service ngSanitize/service/$sanitize ngTouch ngTouch/directive ngTouch/directive/ngClick ngTouch/directive/ngSwipeLeft ngTouch/directive/ngSwipeRight ngTouch/service ngTouch/service/$swipe
watak

AngularJS: API: ngMock/service/$httpBackend


$httpBackend

  1. - service in module ngMock

Fake HTTP backend implementation suitable for unit testing applications that use the $http service.

注意: For fake HTTP backend implementation suitable for end-to-end testing or backend-less development please see e2e $httpBackend mock.

During unit testing, we want our unit tests to run quickly and have no external dependencies so we don’t want to send XHR or JSONP requests to a real server. All we really need is to verify whether a certain request has been sent or not, or alternatively just let the application make requests, respond with pre-trained responses and assert that the end result is what we expect it to be.

This mock implementation can be used to respond with static or dynamic responses via the expect and when apis and their shortcuts (expectGET, whenPOST, etc).

When an Angular application needs some data from a server, it calls the $http service, which sends the request to a real server using $httpBackend service. With 依赖注入, it is easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify the requests and respond with some testing data without sending a request to a real server.

There are two ways to specify what test data should be returned as http responses by the mock backend when the code under test makes http requests:

  • $httpBackend.expect - specifies a request expectation
  • $httpBackend.when - specifies a backend definition

Request Expectations vs Backend Definitions

Request expectations provide a way to make assertions about requests made by the application and to define responses for those requests. The test will fail if the expected requests are not made or they are made in the wrong order.

Backend definitions allow you to define a fake backend for your application which doesn't assert if a particular request was made or not, it just returns a trained response if a request is made. The test will pass whether or not the request gets made during testing.

Request expectations Backend definitions
Syntax .expect(...).respond(...) .when(...).respond(...)
Typical usage strict unit tests loose (black-box) unit testing
Fulfills multiple requests NO YES
Order of requests matters YES NO
Request required YES NO
Response required optional (see below) YES

In cases where both backend definitions and request expectations are specified during unit testing, the request expectations are evaluated first.

If a request expectation has no response specified, the algorithm will search your backend definitions for an appropriate response.

If a request didn't match any expectation or if the expectation doesn't have the response defined, the backend definitions are evaluated in sequential order to see if any of them match the request. The response from the first matched definition is returned.

Flushing HTTP requests

The $httpBackend used in production always responds to requests asynchronously. If we preserved this behavior in unit testing, we'd have to create async unit tests, which are hard to write, to follow and to maintain. But neither can the testing mock respond synchronously; that would change the execution of the code under test. For this reason, the mock $httpBackend has a flush() method, which allows the test to explicitly flush pending requests. This preserves the async api of the backend, while allowing the test to execute synchronously.

Unit testing with mock $httpBackend

The following code shows how to setup and use the mock backend when unit testing a controller. First we create the controller under test:

  // The controller code
  Function MyController($scope, $http) {
    var authToken;

    $http.get('/auth.py').success(Function(data, status, headers) {
      authToken = headers('A-Token');
      $scope.user = data;
    });

    $scope.saveMessage = Function(message) {
      var headers = { 'Authorization': authToken };
      $scope.status = 'Saving...';

      $http.post('/add-msg.py', message, { headers: headers } ).success(Function(response) {
        $scope.status = '';
      }).error(Function() {
        $scope.status = 'ERROR!';
      });
    };
  }

Now we setup the mock backend and create the test specs:

    // testing controller
    describe('MyController', Function() {
       var $httpBackend, $rootScope, createController;

       beforeEach(inject(Function($injector) {
         // Set up the mock http service responses
         $httpBackend = $injector.get('$httpBackend');
         // backend definition common for all tests
         $httpBackend.when('GET', '/auth.py').respond({userId: 'userX'}, {'A-Token': 'xxx'});

         // Get hold of a scope (i.e. the root scope)
         $rootScope = $injector.get('$rootScope');
         // The $controller service is used to create instances of controllers
         var $controller = $injector.get('$controller');

         createController = Function() {
           return $controller('MyController', {'$scope' : $rootScope });
         };
       }));


       afterEach(Function() {
         $httpBackend.verifyNoOutstandingExpectation();
         $httpBackend.verifyNoOutstandingRequest();
       });


       it('should fetch authentication token', Function() {
         $httpBackend.expectGET('/auth.py');
         var controller = createController();
         $httpBackend.flush();
       });


       it('should send msg to server', Function() {
         var controller = createController();
         $httpBackend.flush();

         // now you don’t care about the authentication, but
         // the controller will still send the request and
         // $httpBackend will respond without you having to
         // specify the expectation and response for this request

         $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, '');
         $rootScope.saveMessage('message content');
         expect($rootScope.status).toBe('Saving...');
         $httpBackend.flush();
         expect($rootScope.status).toBe('');
       });


       it('should send auth header', Function() {
         var controller = createController();
         $httpBackend.flush();

         $httpBackend.expectPOST('/add-msg.py', undefined, Function(headers) {
           // check if the header was send, if it wasn't the expectation won't
           // match the request and the test will fail
           return headers['Authorization'] == 'xxx';
         }).respond(201, '');

         $rootScope.saveMessage('whatever');
         $httpBackend.flush();
       });
    });

方法

  • when(method, url, [data], [headers]);

    Creates a new backend definition.

    参数

    参数 类型 详述
    method string

    HTTP method.

    url stringRegExpfunction(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.

    data
    (可选)
    stringRegExpfunction(string)

    HTTP request body or function that receives data string and returns true if the data is as expected.

    headers
    (可选)
    Objectfunction(Object)

    HTTP headers or function that receives http header object and returns true if the headers match the current definition.

    返回值

    requestHandler

    Returns an object with respond method that controls how a matched request is handled.

    • respond – {Function([status,] data[, headers, statusText]) | Function(Function(method, url, data, headers)} – The respond method takes a set of static data to be returned or a function that can return an array containing response status (number), response data (string), response headers (Object), and the text for the status (string).
  • whenGET(url, [headers]);

    Creates a new backend definition for GET requests. For more info see when().

    参数

    参数 类型 详述
    url stringRegExpfunction(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.

    headers
    (可选)
    Objectfunction(Object)

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled.

  • whenHEAD(url, [headers]);

    Creates a new backend definition for HEAD requests. For more info see when().

    参数

    参数 类型 详述
    url stringRegExpfunction(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.

    headers
    (可选)
    Objectfunction(Object)

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled.

  • whenDELETE(url, [headers]);

    Creates a new backend definition for DELETE requests. For more info see when().

    参数

    参数 类型 详述
    url stringRegExpfunction(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.

    headers
    (可选)
    Objectfunction(Object)

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled.

  • whenPOST(url, [data], [headers]);

    Creates a new backend definition for POST requests. For more info see when().

    参数

    参数 类型 详述
    url stringRegExpfunction(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.

    data
    (可选)
    stringRegExpfunction(string)

    HTTP request body or function that receives data string and returns true if the data is as expected.

    headers
    (可选)
    Objectfunction(Object)

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled.

  • whenPUT(url, [data], [headers]);

    Creates a new backend definition for PUT requests. For more info see when().

    参数

    参数 类型 详述
    url stringRegExpfunction(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.

    data
    (可选)
    stringRegExpfunction(string)

    HTTP request body or function that receives data string and returns true if the data is as expected.

    headers
    (可选)
    Objectfunction(Object)

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled.

  • whenJSONP(url);

    Creates a new backend definition for JSONP requests. For more info see when().

    参数

    参数 类型 详述
    url stringRegExpfunction(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled.

  • expect(method, url, [data], [headers]);

    Creates a new request expectation.

    参数

    参数 类型 详述
    method string

    HTTP method.

    url stringRegExpfunction(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.

    data
    (可选)
    stringRegExpfunction(string)Object

    HTTP request body or function that receives data string and returns true if the data is as expected, or Object if request body is in JSON format.

    headers
    (可选)
    Objectfunction(Object)

    HTTP headers or function that receives http header object and returns true if the headers match the current expectation.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled.

    • respond – {Function([status,] data[, headers, statusText]) | Function(Function(method, url, data, headers)} – The respond method takes a set of static data to be returned or a function that can return an array containing response status (number), response data (string), response headers (Object), and the text for the status (string).
  • expectGET(url, [headers]);

    Creates a new request expectation for GET requests. For more info see expect().

    参数

    参数 类型 详述
    url stringRegExpfunction(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.

    headers
    (可选)
    Object

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled. See #expect for more info.

  • expectHEAD(url, [headers]);

    Creates a new request expectation for HEAD requests. For more info see expect().

    参数

    参数 类型 详述
    url stringRegExpfunction(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.

    headers
    (可选)
    Object

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled.

  • expectDELETE(url, [headers]);

    Creates a new request expectation for DELETE requests. For more info see expect().

    参数

    参数 类型 详述
    url stringRegExpfunction(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.

    headers
    (可选)
    Object

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled.

  • expectPOST(url, [data], [headers]);

    Creates a new request expectation for POST requests. For more info see expect().

    参数

    参数 类型 详述
    url stringRegExpfunction(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.

    data
    (可选)
    stringRegExpfunction(string)Object

    HTTP request body or function that receives data string and returns true if the data is as expected, or Object if request body is in JSON format.

    headers
    (可选)
    Object

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled.

  • expectPUT(url, [data], [headers]);

    Creates a new request expectation for PUT requests. For more info see expect().

    参数

    参数 类型 详述
    url stringRegExpfunction(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.

    data
    (可选)
    stringRegExpfunction(string)Object

    HTTP request body or function that receives data string and returns true if the data is as expected, or Object if request body is in JSON format.

    headers
    (可选)
    Object

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled.

  • expectPATCH(url, [data], [headers]);

    Creates a new request expectation for PATCH requests. For more info see expect().

    参数

    参数 类型 详述
    url stringRegExpfunction(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.

    data
    (可选)
    stringRegExpfunction(string)Object

    HTTP request body or function that receives data string and returns true if the data is as expected, or Object if request body is in JSON format.

    headers
    (可选)
    Object

    HTTP headers.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled.

  • expectJSONP(url);

    Creates a new request expectation for JSONP requests. For more info see expect().

    参数

    参数 类型 详述
    url stringRegExpfunction(string)

    HTTP url or function that receives the url and returns true if the url match the current definition.

    返回值

    requestHandler

    Returns an object with respond method that control how a matched request is handled.

  • flush([count]);

    Flushes all pending requests using the trained responses.

    参数

    参数 类型 详述
    count
    (可选)
    number

    Number of responses to flush (in the order they arrived). If undefined, all pending requests will be flushed. If there are no pending requests when the flush method is called an exception is thrown (as this typically a sign of programming error).

  • verifyNoOutstandingExpectation();

    Verifies that all of the requests defined via the expect api were made. If any of the requests were not made, verifyNoOutstandingExpectation throws an exception.

    Typically, you would call this method following each test case that asserts requests using an "afterEach" clause.

      afterEach($httpBackend.verifyNoOutstandingExpectation);
  • verifyNoOutstandingRequest();

    Verifies that there are no outstanding requests that need to be flushed.

    Typically, you would call this method following each test case that asserts requests using an "afterEach" clause.

      afterEach($httpBackend.verifyNoOutstandingRequest);
  • resetExpectations();

    Resets all request expectations, but preserves all backend definitions. Typically, you would call resetExpectations during a multiple-phase test when you want to reuse the same instance of $httpBackend mock.


Artikel sebelumnya: Artikel seterusnya: