Sinon - Stub模块功能,无需依赖注入即可对其进行测试

时间:2017-11-07 12:11:21

标签: javascript node.js unit-testing sinon stub

我有一个代理模块,它将函数调用转发给服务。我想测试是否在调用此代理模块中的函数时调用服务函数。

这是代理模块:

const payService = require('../services/pay')
const walletService = require('../services/wallet')

const entity = {
    chargeCard: payService.payByCardToken,
    // ... some other fn
}

module.exports = entity

基于this examplethis response,我尝试存根所需的模块' payService':

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()

    })
})

但测试失败了:

  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模块并非真正存根。我知道如果我将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)

但该代码仅用于测试目的。有没有办法在没有依赖注入和变通方法的情况下存根模块功能?

1 个答案:

答案 0 :(得分:4)

问题是,在payService已经设置了映射后,您在entity存根const expect = require('expect.js') const sinon = require('sinon') const payService = require('../../services/pay') describe('Payment entity,', () => { let entity before(() => { sinon.stub(payService, 'payByCardToken') entity = require('../entity') }) it('should proxy functions to each service', () => { entity.chargeCard() expect(payService.payByCardToken.called).to.be.ok() }) })

如果你改变你的测试代码:

entity

...您应该发现volley使用您的存根函数设置自己,并且断言通过正常。