具有以下balanceRepository.js文件。
module.exports = function(){
this.getBalance = (accountId)=>{
throw 'NotImplementedException';
};};
还有服务transactionService.js文件。
module.exports = function(balanceRepo){
this.isTransactionAllowed = (amount, accountId)=>{
const balance = balanceRepo.getBalance(accountId);
return amount <= balance;
};};
我想进行单元测试,当我们调用transactionService.isTransactionAllowed时,它将在内部调用balanceRepository.getBalance。我期待以下代码能正常工作。
let BalanceRepository = require('../balanceRepository');
let TransactionService = require('../transactionService');
let should = require('should');
let sinon = require('sinon');
describe('transaction service', ()=>{
let fakeBalanceRepo = sinon.spy(BalanceRepository);
let transactionSrv = new TransactionService(fakeBalanceRepo);
transactionSrv.isTransactionAllowed(100, 987654321);
it('should call getBalance', ()=>{
fakeBalanceRepo.getBalance.should.be.called();
});});
我创建了类BalanceRepository的间谍。我将那个间谍对象注入到我的TransactionService的实际实现中。然后,我断言在间谍程序上调用了getBalance方法。这对我来说很有意义,但是没有用!!
如何注入伪造品并断言其方法之一被称为?
答案 0 :(得分:2)
sinon.spy(BalanceRepository)
并不意味着会自动侦听类方法(不会)。
TransactionService
期望BalanceRepository
实例,而fakeBalanceRepo
是构造函数。
如果目的是监视类方法而不改变其行为,则为:
let balanceRepo = new BalanceRepository;
sinon.spy(balanceRepo, 'isTransactionAllowed')
let transactionSrv = new TransactionService(balanceRepo);
transactionSrv.isTransactionAllowed(100, 987654321);
balanceRepo.getBalance.should.be.called();
答案 1 :(得分:0)
这是发情期所评论的。
let balanceRepo = new BalanceRepository();
let fakeGetBalance = sinon.stub(balanceRepo, 'getBalance');
let transactionSrv = new TransactionService(balanceRepo);
transactionSrv.isTransactionAllowed(100, 987654321);
it('should call getBalance', ()=>{
fakeGetBalance.should.be.called();
});