angularjs - angular JS mock json unit testing -
var app= angular.module('app', []); below factory method data 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 retrieve data'); }); } } }); below controller. can able access service data in 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+ " , duration " + $scope.duration); }); }]); below sample.json
{ "status": 200, "projectdetails": { "name": "project name", "duration": "4 months", "business_place": "dummy address" } } how write unit test cases above service. test projectdetails.name in test cases.
to mock http responses can use $httpbackend service. example, if want test getmydata method of object created factory, you'd like:
var $httpbackend, factorygetjsonfile; var sample.json = // 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 server's response $httpbackend.when('get', geturl). respond(sample.json); })); it('factorygetjsonfile.getmydata should make correct request', function() { // call services method , flush $httpbackend mock response sent var response = factorygetjsonfile.getmydata(); $httpbackend.flush(); expect(response).toequal(jasmine.objectcontaining(sample.json)); });
Comments
Post a Comment