我是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);
});
但是这个断言失败了。我究竟做错了什么?请帮助:)
答案 0 :(得分:5)
您的代码存在一些问题
sinon.spy(PaymentService, 'start');
我在http://plnkr.co/edit/AvqS3L?p=preview
创建了上面的工作插件这是更新的测试代码:
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);
});
});