0

我第一次在 Stack 上写一个问题;)我在测试 $mdSidenav (角度材料组件。请参阅https://material.angularjs.org/)时遇到问题。在我的控制器中,我有类似的东西:

$scope.toggleRight = function() {
    $mdSidenav('right').toggle();
};

我想测试一下。所以在我的测试文件中,我首先创建了这个对象的模拟:

var $mdSidenav = function(test){
        return {
            toggle: function(){
                return true;
            }
        };
    };

    beforeEach(inject(function ($controller) {
        $scope = $rootScope.$new();
        createController = function () {
            return $controller('headerCtrl', {
                '$scope': $scope,
                '$mdSidenav': $mdSidenav
            });
        };
    }));

然后我正在尝试测试它:

describe('toggleRight method', function(){
        beforeEach(function(){
            spyOn($mdSidenav('right'), 'toggle').and.callThrough();
        });

        it('Should toggleRight open/close', function(){
            $scope.toggleRight();
            expect($mdSidenav('right').toggle).toHaveBeenCalled();
        });

    });

但是业力向我发送这个错误:

错误:预期是间谍,但得到了功能。

我希望有人可以帮助我;)

4

1 回答 1

1

You could try a different approach, use $provide and an anonymous module to inject the mock.

I'm using sinon here, but you can change to the appropriate Jasmine code:

var spy = sinon.spy();

beforeEach(module(function ($provide) {
  $provide.value('$mdSidenav', function (v) {
    return {
      toggle: spy
    }
  });
}));

Then in the test:

sinon.assert.calledOnce(spy);
于 2015-04-13T16:26:54.703 回答