Sinon to stub AngularJS service in Tests Sinon to stub AngularJS service in Tests angularjs angularjs

Sinon to stub AngularJS service in Tests


You don't stub out the whole service rather the methods on that service you want to assert on. so you let angular do the injection normally and then stub the methods out on the service you get from the $injector i.e. you don't have to do anything funky as the services are singletons within the scope of a single test.

I always create a sinon sandbox and mock things on that - then in the after each test you can restore all the mocked methods

var sandbox, myService, somethingUnderTest;beforeEach(module('myModule'));describe('something', function () {    beforeEach(inject(function ($injector) {        sandbox = sinon.sandbox.create();        myService = $injector.get('myService');        somethingUnderTest = $injector.get('somethingUnderTest');    }));    afterEach(function () {        sandbox.restore();    });    it('should be defined', function () {        expect(somethingUnderTest).to.exist;    });    describe('someMethod', function () {        it('should call the start method on myService', function () {            sandbox.stub(myService, 'start');            somethingUnderTest.start();            expect(myService.start.calledOnce).to.equal(true);        });    });});