Reputation: 821
var app= angular.module('app', []);
below is my factory method that will get the data from the sample.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');
});
}
}
});
below is my controller. I can able to access the service data in my controller
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);
});
}]);
Below is my sample.json
{
"status": 200,
"projectDetails": {
"name": "Project Name",
"duration": "4 Months",
"business_place": "Dummy address"
}
}
How to write the unit test cases for the above get service. I would like to test projectDetails.name in my test cases.
Upvotes: 0
Views: 2076
Reputation: 123
To mock http responses you can use the $httpbackend service. For example, if you want to test the getMyData
method of the object created by your factory, you'd do something like:
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));
});
Upvotes: 1