私はサービスコールをサービスに転送するプロキシモジュールを持っています。このプロキシモジュール内の関数が呼び出されたときに、サービス関数が呼び出されたかどうかをテストします。ここでSinon - スタブモジュールの機能とそれを依存性の注入なしでテストする
は、プロキシモジュールです:
const expect = require('expect.js')
const sinon = require('sinon')
const entity = require('../entity')
const payService = require('../../services/pay')
describe('Payment entity,',() => {
it('should proxy functions to each service',() => {
const stub = sinon.stub(payService, 'payByCardToken')
entity.chargeCard()
expect(payService.payByCardToken.called).to.be.ok()
})
})
しかし、テストがで失敗します:this exampleとthis responseに基づいて
const payService = require('../services/pay')
const walletService = require('../services/wallet')
const entity = {
chargeCard: payService.payByCardToken,
// ... some other fn
}
module.exports = entity
、私は必要なモジュールのpayService」をスタブにしてみました
0 passing (19ms)
1 failing
1) Payment entity,
should proxy functions to each service:
Error: expected false to be truthy
at Assertion.assert (node_modules/expect.js/index.js:96:13)
at Assertion.ok (node_modules/expect.js/index.js:115:10)
at Function.ok (node_modules/expect.js/index.js:499:17)
at Context.it (payments/test/entity.js:14:56)
これは、payServiceモジュールが本当にスタブではないためですベッド。
// entity
const entity =() => {
return {
payService,
chargeCard: payService.payByCardToken,
// .. some other fn
}
}
// test
const stub = sinon.stub(payService, 'payByCardToken')
entity().chargeCard()
expect(payService.payByCardToken.called).to.be.ok()
// test output
Payment entity,
✓ should proxy functions to each service
1 passing (8ms)
をしかし、それは唯一のテストpuposesのために追加のコードです:私は、エンティティのプロパティとしてpayServiceを追加し、機能ですべてを包む場合、テストは合格します知っています。依存性注入や回避策なしでモジュール関数をスタブする方法はありますか?
はい、これは、ありがとうございました! – AFMeirelles