javascript - Jasmine - Test a service that returns a localStorage item -
javascript - Jasmine - Test a service that returns a localStorage item -
i have authentication service stores current user object in localstorage when user logs in successfully. service used many other services. service, abcservice calls method in authentication service token required communication. spec abcservice fails in grunt test, , says this:
typeerror: 'null' not object (evaluating 'abcconfig.getuser().token')
obviously token set when user logged in. how rid of this? or in other words, how test right?
to solve issue can emulate logged in state false local storage entry along lines of this:
describe("when user logged in", function () { beforeeach(function () { // ensure user logged in localstorage.setitem('loggedin', 'testuser'); }); it("should work", function () { // run function, should work }); });
it opens possibility test how service behaves if there no user info in localstorage
:
describe("when user logged out", function () { beforeeach(function () { localstorage.removeitem('loggedin'); }); it("should fail", function () { // along lines of // expect(abcconfig.getuser().token).tobenull(); }); });
in regards question async calls, jasmine in 2.0.0+ provides callback method argument of it
, beforeeach
, aftereach
anonymous functions. looks this:
describe("when user logged in", function () { beforeeach(function (done) { // ensure user logged in loginfunction(done); // pass done callback }); it("should work", function () { // run function, should work }); });
with this, tests proceed 1 time done
callback has been called in beforeeach
block.
more info here.
javascript angularjs unit-testing jasmine angularjs-service
Comments
Post a Comment