Node.js 使用Sinon.js模拟要注入的依赖项
具有以下balanceRepository.js文件Node.js 使用Sinon.js模拟要注入的依赖项,node.js,unit-testing,mocha.js,sinon,should.js,Node.js,Unit Testing,Mocha.js,Sinon,Should.js,具有以下balanceRepository.js文件 module.exports = function(){ this.getBalance = (accountId)=>{ throw 'NotImplementedException'; };}; 以及服务transactionService.js文件 module.exports = function(balanceRepo){ this.isTransactionAllowed = (amount, accountId)
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;
};};
我创建了一个BalancerPository类的间谍。我将间谍对象注入到TransactionService的实际实现中。然后,我断言在spy上调用了getBalance方法。这对我来说是有道理的,但它不起作用
我怎样才能注入一个伪函数并断言它的一个方法被调用?sinon.spy(BalanceRepository)
并不意味着类方法将被自动监视(它们不会)
TransactionService
需要BalancerPository
实例,而FakeBalancerPo
是构造函数
如果目的是监视类方法而不改变其行为,则:
let balanceRepo = new BalanceRepository;
sinon.spy(balanceRepo, 'isTransactionAllowed')
let transactionSrv = new TransactionService(balanceRepo);
transactionSrv.isTransactionAllowed(100, 987654321);
balanceRepo.getBalance.should.be.called();
正如埃斯图所评论的那样
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();
});
我试过了,但也没用。如果我们将BalancerPository的真正实现注入TransactionService,它将调用真正的getBalance抛出“NotImplementedException”。在真实场景中,用户将尝试连接到数据库。很明显,我们不希望在单元测试中出现这种情况。我遗漏了什么吗?不清楚原始代码有什么问题。是的,在单元测试中,存根DB调用是可取的。如果需要模拟实现,请使用
sinon.stub
,而不是sinon.spy
。
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();
});