2015-08-14 43 views
1

我试图窥探在控制器中定义的方法工作,但无论我做什么,我看到测试失败与消息:间谍不是角,茉莉花和兴农

Error: Expected a spy, but got Function.

我使用Karma,Jasmine和Sinon与Angular一起。我非常确定事情的设置是否正确,因为刚刚读取$ scope范围内的属性的测试通过。

例如,我有这个非常简单的应用程序模块:

angular.module('app', []);

而这个简单的控制器:

angular.module('app').controller('myController', ['$scope', function($scope) { 
    $scope.test = ''; 
    $scope.setTest = function (newString) { 
     $scope.test = newString || 'default'; 
    } 
    $scope.updateTest = function (newString) { 
     $scope.setTest(newString); 
    }; 
}]); 

我的规格文件如下:

describe('myController', function() { 
    'use strict'; 

    beforeEach(module('app')); 

    var $scope, sandbox; 

    beforeEach(inject(function ($controller) { 
     $scope = {}; 
     $controller('myController', { $scope: $scope }); 

     sandbox = sinon.sandbox.create(); 
    })); 

    afterEach(function() { 
     sandbox.restore(); 
    }); 

    describe('#updateTest()', function() { 

     beforeEach(function() { 
      sandbox.spy($scope, 'setTest'); 
     }); 

     it('updates the test property with a default value', function() { 
      $scope.updateTest(); 

      expect($scope.test).toEqual('default'); 
     }); 

     it('calls the setTest method', function() { 
      $scope.updateTest(); 

      expect($scope.setTest).toHaveBeenCalled(); 

     }); 

    }); 
}); 

第一个测试(它只是检查测试属性会得到你通过)。

第二个测试,我只是想窥探setTest()方法,失败并显示上面的错误消息。

如果我注销$scopebeforeEach我可以看到setTest方法,并且没有脚本错误。

我错过了什么?

回答

2

我想这是因为你在混合茉莉花和Sinon,我不认为Sinon间谍sandbox.spy()会与Jasmine匹配器expect().toHaveBeenCalled()一起工作。你应该选择使用哪一个:

  1. 使用兴农间谍和结果转换为原始将它传递给茉莉:

    sandbox.spy($scope, 'setTest'); 
    expect($scope.setTest.called).toBeTruthy(); 
    

    但是这种做法会给你少量输出:Expected true to be false,而不是通常的Expected spy to have been called

  2. 使用茉莉花间谍:

    spyOn($scope, 'setTest'); 
    expect($scope.setTest).toHaveBeenCalled(); 
    

您也可以看看该工具jasmine-sinon,这增加了额外的茉莉花的匹配,并允许使用兴农间谍与间谍茉莉花匹配器。因此,你应该能够像你的样品一样使用:

sandbox.spy($scope, 'setTest'); 
expect($scope.setTest).toHaveBeenCalled(); 
+0

辉煌,我忘了这个包!我将安装它并尝试使其工作。我以前面例子中的方式使用了Karma/Jasmine/Sinon,但我并没有参与设置.... – danwellman

+0

是的,就是这样,谢谢先生!另外,我必须通过将它添加到Karma加载的文件列表中来加载Karma中的文件。 – danwellman