2013-12-17 30 views
3

我是AngularJS的新手。Mockjax在角度應用中的使用

我可以通過使用$ http services method get/post調用模擬終點來在AngularJS中使用mockjax。 如果沒有方法$ http提供了一種方法來創建終點並調用它們?

例如 的MockService是這樣

$.mockjax({ 
    url: '/sometest/abc', 
    type: 'post', 
    responseTime: 2000, 
    responseText: { 
     LoginSuccessful: true, 
     ErrorMessage: "Login Successfuly", 
     Token: "P{FsGAgtZT7T" 
    } 
}); 

而且,我已經創造瞭如下面DataService的。

'use strict'; 

//Data service 
angular.module('app').factory('dataService',['$http', function($http){ 

    var restCall = function (url, type, data, successCallback, errorCallback) { 
     $http({ 
      method: type, 
      url: url, 
      data: data, 
     }). 
     success(function (data, status, headers, config) { 
      successCallback(data); 
     }). 
     error(function (data, status, headers, config) { 
      errorCallback(data) 
     }); 
    }; 

    return { 
     getTemplate: function (success, error) { 
      restCall('/sometest/abc', 'GET', null, success, error); 
    } 
    }; 
}]); 

而且控制器下面是

angular.module('App').controller('mainCtrl', ['$scope', 'trackService', 'dataService', 
     function ($scope, TrackService, ds) { 

      ds.getTemplate(function (data) { 
       //do some calculation 
      }, function() { 
       console.warn('Something is not right'); 
      });}]); 

我想知道,這是使用$ HTTP的正確方法,還是其他什麼東西應該是done.This是我想實現在實際的代碼中,而不是在使用茉莉花的單元測試中。

+0

您是否試圖模擬HTTP調用進行測試? –

+0

是的,我做 早些時候我使用jquery ajax調用mockjax端點,但現在我需要使用$ http角度調用它們。 – Mozak

回答

1

I had to do this recently我發現使用Angular的內置東西(angular-mocks)非常容易。

這裏的基本思想是:您在您的測試工具的獨立模塊,嘲笑你的要求,這是一個基本的URL匹配用字符串或正則表達式...

// in some other file that you include only for tests... 
var myTestApp = angular.module('myApp', ['myApp']); 

myTestApp 
    .config(function ($provide, $httpProvider) { 
    // Here we tell Angular that instead of the "real" $httpBackend, we want it 
    // to use our mock backend 
    $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator); 
    }) 
    .run(function ($httpBackend) { 

    $httpBackend.whenGET('/some/url') 
     .respond(function (method, url, requestData, headers) { 
     // Do whatever checks you need to on the data, headers, etc 

     // Then return whatever you need to for this test. 
     // Perhaps we want to test the failure scenario... 
     return [ 
      200,      // Status code 
      { firstname: 'Jordan' }, // Response body 
      {}       // Response headers 
     ]; 
     }); 
    }); 

檢查上面的第一個鏈接閱讀我的博客文章。