angularjs - $httpBackend mock responds with more than what I tell it to? -
i have jasmine test 1 of angular services fetches data server , makes publicly accessible. server returns json, array of objects [{...}, {...}, ...]
.
now tried writing test mocked out http backend:
var mocklibrary = [{}, {}]; beforeeach(inject(function(librarysvc) { libsvc = librarysvc; })); it('should fetch library', function(done) { inject(function($httpbackend) { $httpbackend.expectget('/library').respond(200, mocklibrary); libsvc.getlibrary() .then(function(response) { expect(_.isequal(response, mocklibrary)).tobetruthy(); }) .finally(done); $httpbackend.flush(); }); });
the code in service follows:
var library; var deferred = $q.defer(); $http.get('/library') .then(function(data) { library = data; deferred.resolve(library); }, function(err) { deferred.reject(err); });
so, service assigns json response body of server internal library
variable , resolves promise it. when running test, fails, because response
in test not equal mocklibrary
. instead, response
this:
object{data: [object{}, object{}], status: 200, headers: function (c){ ... }, config: object{method: 'get', transformrequest: [...], transformresponse: [...], url: '/library', headers: object{accept: ...}}, statustext: ''}
and wanted response.data
in test, , data.data
in service logic.
why angular this? implicitly suggesting json responses server should hash holds actual response data in data
attribute? why ever want adjust service logic angular test? or did miss something? docs $httpbackend weren't helpful on matter.
further notes: i'm using underscore.js deep equals check @ _.isequal(...)
, , jasmine 2.0 test asynchronously (thus function(done)
syntax).
when using .then()
$http
, first parameter won't data server.
it wrapper object see , data server in .data
.
there no different between service , test. might confused , think data
parameter in service data server, isn't.
therefore, yes, have use response.data
in test , data.data
in service. suggest rename data
parameter in service response
consistency.
also see: $http documentation
Comments
Post a Comment