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

AFM*_*les 5 javascript unit-testing stub node.js sinon

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

这是代理模块:

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

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

module.exports = entity
Run Code Online (Sandbox Code Playgroud)

基于此示例此响应,我尝试对所需的模块“ 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()

    })
})
Run Code Online (Sandbox Code Playgroud)

但是测试失败并显示:

  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)
Run Code Online (Sandbox Code Playgroud)

那是因为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)
Run Code Online (Sandbox Code Playgroud)

但这只是为了测试目的而添加的代码。有没有一种方法可以在没有依赖项注入和变通方法的情况下对模块功能进行存根?

Phi*_*oth 5

问题是payServiceentity设置了映射之后,您太迟了。

如果您像这样更改测试代码:

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()
    })
})
Run Code Online (Sandbox Code Playgroud)

...您应该发现可以entity使用存根函数设置自身,并且断言可以通过。