i reading posts related don't repeat question.
i have next unit testing code:
describe('service', function() { var questionapiservice; beforeeach(module('myapp')); beforeeach(inject(function (_questionapiservice_) { questionapiservice = _questionapiservice_; })); // test service availability it('check existence of field question service', inject(function(questionapiservice) { //expect(1).toequal(100); questionapiservice.getfield() .then(function(data) { //console.log(data); expect(1).toequal(100); }); }));
});
if run code expect(1).toequal(100);
outside service, result error, if write same code expect(1).toequal(100);
inside service, result success, makes me think validator not entering service.
whats wrong?
edit 1:
hello asta, think ur idea , i'm trying implement it. have error in code , don't know how debugging:
defer = $q.defer(); spyon(questionapiservice, 'getfield').andreturn(defer.promise); defer.resolve(data); expect(data.nextq).toequal(1);
my unit testing fails. if promise successful, "data" object must have nextq attribute.
edit 2:
hi asta, code amazing. i'm trying execute code in system , still error. ut fails:
error: unexpected request: http://mi.url.com/api/thefield no more request expected
do u know what's wrong? clarify code works fine on application ut problem.
question api service code:
angular.module('myapp.services') .factory('questionapiservice', function($http, $q) { var myservice = { getfield: function() { var defer = $q.defer(); $http.get('http://mi.url.com/api/thefield') .success( function(data) { defer.resolve(data); }) .error( function(data) { defer.reject(data); }); return defer.promise; }; return myservice; });
your test:
describe('myapp', function () { beforeeach(function () { module('myapp'); }); describe('questionapiservice', function () { it('should check existence of field question service', inject(function($rootscope, questionapiservice) { var response = null; var promise = questionapiservice.getfield(); promise.then(function(data) { response = data; }); $rootscope.$apply(); var expectedresponse = { "nextq": 1 }; console.log(response); //expect(json.parse(response.nextq)).toequal(expectedresponse.nextq); })); }); });
i think need move expectation outside then
, $rootscope.$apply()
.
it('should check existence of field question service', inject(function($rootscope, questionapiservice) { response = null; promise = questionapiservice.getfield() promise.then(function(data) { response = data; }); $rootscope.$apply(); expectedresponse = { "nextq": "value" } expect(json.parse(response)).toequal(expectedresponse); }));
i created jsfiddle can use play around with. sets service returns json via promise used test http://jsfiddle.net/neridum/9uumwfzc/
alternatively if want test service service can mock out using spies. here mock response promise , resolve it
defer = $q.defer(); spyon(questionapiservice, 'getfield').andreturn(defer.promise); defer.resolve(data); expect(data).toequal('100');