【问题标题】:AngularJs Testing Sinon spyAngularJs 测试 Sinon spy
【发布时间】:2015-02-01 15:42:39
【问题描述】:

我是Sinon的新手,所以我想检查是否正在调用特定函数,这就是我得到的:

terminalController.controller('CashAcceptorController', [
    'PaymentService',
    '$rootScope',
    '$scope',
    'PayingInfo',
    '$interval',
    '$location',
    function (PaymentService, $rootScope, $scope, PayingInfo, $interval, $location) {
     PaymentService.start();
....
]);

在测试中,我尝试检查是否在控制器实例化时调用了 PaymentService.start():

describe('CashAcceptorController', function() {

var PaymentService, rootScope, scope, PayingInfo, $interval, $location;
var mySpy  = sinon.spy(PaymentService.start());;
beforeEach(module('eshtaPayTerminalApp.controllers'));

beforeEach(module('eshtaPayTerminalApp.services'));


beforeEach(inject(function($controller, 
        $rootScope, _PaymentService_, _$interval_, _PayingInfo_) {

    $interval = _$interval_;
    scope = $rootScope.$new();
    rootScope = $rootScope.$new();
    PaymentService = _PaymentService_;
    PayingInfo = _PayingInfo_;

    rootScope.serviceNumber = 'm1';
    rootScope.phoneNumber =  '05135309';

    $controller('CashAcceptorController', {
        $rootScope : rootScope,
        $scope : scope,
        $location : $location,
        _PaymentService_ : PaymentService,
        _$interval_:$interval,
        _PayingInfo_:PayingInfo
        });

}));


it('should call start paying', function() {
            expect(mySpy.callCount).to.equal(1);
        });

但是这个断言失败了。我究竟做错了什么?请帮忙:)

【问题讨论】:

    标签: angularjs sinon


    【解决方案1】:

    您的代码存在一些问题

    • 需要先分配 PaymentService 对象,然后才能对其进行监视
    • 要使用 sinon 添加间谍,您需要将方法名称作为字符串传递,例如。 sinon.spy(PaymentService, 'start');

    我已经在http://plnkr.co/edit/AvqS3L?p=preview 上创建了上述的工作 plunk

    这是更新后的测试代码:

    describe('CashAcceptorController', function() {
    
      var PaymentService;
      var $controller;
    
      beforeEach(module('eshtaPayTerminalApp.controllers'));
      beforeEach(module('eshtaPayTerminalApp.services'));
    
      beforeEach(inject(function(_PaymentService_, _$controller_) {
        PaymentService = _PaymentService_;
        $controller = _$controller_;
      }));
    
      it('should call start paying', function() {
        var mySpy = sinon.spy(PaymentService, 'start');
        $controller('CashAcceptorController', { PaymentService: PaymentService });
        
        chai.expect(mySpy.callCount).to.equal(1);
        
        // another way of checking that it was called once
        chai.assert(PaymentService.start.calledOnce);
      });
    });

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-18
      • 1970-01-01
      • 1970-01-01
      • 2017-02-12
      • 1970-01-01
      • 2017-09-19
      • 1970-01-01
      • 2014-09-08
      相关资源
      最近更新 更多