2015-09-30 65 views
0
var app= angular.module('app', []); 

下面是我廠方法將從sample.json角JS模擬JSON單元測試

app.factory('factoryGetJSONFile', function($http) { 
    return { 
    getMyData: function(done) { 
     $http.get('mock/sample.json') 
     .success(function(data) { 
     done(data); 
     }) 
     .error(function(error) { 
     alert('An error occured whilst trying to retrieve your data'); 
     }); 
    } 
    } 
}); 

得到下面的數據是我的控制器。我能夠訪問我的控制器

app.controller('homeController', ['$scope', 'factoryGetJSONFile', function ($scope, factoryGetJSONFile) { 

    factoryGetJSONFile.getMyData(function (data) { 
     $scope.name = data.projectDetails.name; 
     $scope.duration = data.projectDetails.duration; 
     console.log($scope.name+ " and duration is " + $scope.duration); 
    }); 

}]); 

服務數據下面是我sample.json

{ 
    "status": 200, 
    "projectDetails": { 
     "name": "Project Name", 
     "duration": "4 Months", 
     "business_place": "Dummy address" 
    } 
} 

如何編寫單元測試的情況下對上述獲得服務。我想在我的測試用例中測試projectDetails.name。

+0

你可以在這裏找到[鏈接](http://jsfiddle.net/seshuggina/5u7L8mou/2 /) http://jsfiddle.net/seshuggina/5u7L8mou/2/ – Seshu

回答

1

要模擬http響應,您可以使用$httpbackend服務。例如,如果你想測試你的工廠創建的對象的getMyData方法,你會做這樣的事情:

var $httpbackend, 
factoryGetJSONFile; 

var sample.json = // Your sample JSON 
var getUrl = 'mock/sample.json'; 

beforeEach(inject(function(_$httpbackend_, _factoryGetJSONFile_) { 
    // Load app 
    module('app'); 
    // Make services available in tests 
    $httpbackend = _$httpbackend_; 
    factoryGetJSONFile = _factoryGetJSONFile; 

    // Mock the server's response 
    $httpbackend.when('GET', getUrl). 
     respond(sample.json); 

})); 

It('factoryGetJSONFile.getMyData should make correct GET request', function() { 
    // Call your services method and flush $httpbackend so the mock response is sent 
    var response = factoryGetJSONFile.getMyData(); 
    $httpBackend.flush(); 

    expect(response).toEqual(jasmine.objectContaining(sample.json)); 
}); 
+0

它不工作..其投擲以下錯誤 factoryGetJSONFile.getMyData應該做出正確的GET請求 – Seshu

+0

請幫嘗試在以下網址:http://jsfiddle.net/seshuggina/5u7L8mou/4/ – Seshu

+0

拋出什麼錯誤?你給的只是測試的描述。你需要安裝ngMocks來使用$ httpbackend,所以檢查你的karma.conf.js文件中是否包含'angular-mocks.js'。 –