Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sinon to stub AngularJS service in Tests

Instead of creating a mock service manually like:

var mockService = { GetData: function() { deferred = $q.defer(); return deferred.promise; }

And then adding it to my $controller injection like:

$controller('mycontroller', { $scope: scope, myService: mockService });

How can I stub out my real service using Sinon and inject that stubbed service where "mockService" is being injected into my controller above? I'd like to stub out my real service in case my service methods get renamed then my controller tests will fail along with my service tests.

Thanks in advance and I hope this makes sense.

like image 472
Steven Rogers Avatar asked Jul 16 '14 20:07

Steven Rogers


1 Answers

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);
        });
    });
});
like image 74
Jon Avatar answered Sep 20 '22 18:09

Jon