Sinon在测试中存根AngularJS服务

Ste*_*ers 8 testing sinon angularjs

而不是手动创建模拟服务,如:

var mockService = { GetData: function() { deferred = $q.defer(); return deferred.promise; }
Run Code Online (Sandbox Code Playgroud)

然后将它添加到我的$ controller注入中,如:

$controller('mycontroller', { $scope: scope, myService: mockService });
Run Code Online (Sandbox Code Playgroud)

如何使用Sinon来存储我的真实服务并注入那个"mockService"被注入上面的控制器的存根服务?我想把我的真实服务存根,以防我的服务方法被重命名,然后我的控制器测试将失败以及我的服务测试.

提前谢谢,我希望这是有道理的.

Jon*_*Jon 17

您不会将整个服务存根,而不是您想要断言的服务上的方法.所以你让角度正常进行注射然后将方法存在于你从$ injector获得的服务上,即你不需要做任何时髦的事情,因为服务是单一测试范围内的单例.

我总是创建一个sinon沙箱并在其上模拟东西 - 然后在每次测试之后你可以恢复所有模拟的方法

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);
        });
    });
});
Run Code Online (Sandbox Code Playgroud)