Skip to content

Instantly share code, notes, and snippets.

@avanslaars
Last active August 29, 2015 14:17
Show Gist options
  • Save avanslaars/a7df470ec6219bfb742b to your computer and use it in GitHub Desktop.
Save avanslaars/a7df470ec6219bfb742b to your computer and use it in GitHub Desktop.
Simple example of unit testing run block in angular
describe('run block', function(){
var sandbox,
MockCookieStore,
MockAuthService,
token
beforeEach(function(){
sandbox = sinon.sandbox.create()
MockCookieStore = sandbox.stub({get:function(key){}})
MockAuthService = sandbox.stub({LoadToken:function(uObj){}})
token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOjEyMzQ1Njc4OTAsIm5hbWUiOiJKb2huIERvZSIsImFkbWluIjp0cnVlfQ.eoaDVGTClRdfxUZXiPs3f8FmJDkDE_VCQFXqKxpLsts'
module('MyApplication',function($provide){
$provide.value('$cookieStore',MockCookieStore)
$provide.value('AuthService',MockAuthService)
})
})
afterEach(function(){
sandbox.restore()
})
it('should check for a token cookie and load it if found', function(done){
MockCookieStore.get.returns(token)
inject() //THIS IS THE KEY!
expect(MockCookieStore.get).to.have.been.calledWith('auth-token')
expect(MockAuthService.LoadToken).to.have.been.calledWith(token)
done()
})
it('should not try to load a token when one is not found', function(done){
MockCookieStore.get.returns(undefined)
inject() //THIS IS THE KEY!
expect(MockCookieStore.get).to.have.been.calledWith('auth-token')
expect(MockAuthService.LoadToken).not.to.have.been.called
done()
})
})
(function () {
angular.module('MyApplication')
.run(appStartup)
appStartup.$inject = ['$cookieStore', 'AuthService']
function appStartup($cookieStore, AuthService)
{
var token = $cookieStore.get('auth-token')
if(token){
AuthService.LoadToken(token)
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment