How to spy on an imported function using Sinon?

≡放荡痞女 提交于 2019-12-12 13:34:14

问题


Let's say we want to test that a specific function is called by another function using Sinon.

fancyModule.js

export const fancyFunc = () => {
  console.log('fancyFunc')
}

export default const fancyDefault = () => {
  console.log('fancyDefault')
  fancyFunc()
}

fancyModule.test.js

import sinon from 'sinon'
import fancyDefault, { fancyFunc } from '../fancyModule'

describe('fancyModule', () => {
  it('calls fancyFunc', () => {
    const spy = sinon.spy(fancyFunc)
    fancyDefault()
    expect(spy.called).to.be.true
  })
})

When I run this test the actual value is always false. Also, the original function fancyFunc() gets invoked (outputs fancyFunc) instead of being mocked.


回答1:


You can change the import style, and import your module as an Object like this

import sinon from 'sinon'
import * as myModule from '../fancyModule'

describe('fancyModule', () => {
  it('calls fancyFunc', () => {
    const spy = sinon.spy(myModule, 'fancyFunc');
    myModule.fancyDefault()
    expect(spy.called).to.be.true
  })
})



回答2:


You should use https://github.com/speedskater/babel-plugin-rewire/

import sinon from 'sinon'
import fancyDefault, { __RewireAPI__ } from '../fancyModule'

describe('fancyModule', () => {
  it('calls fancyFunc', () => {
    const spy = sinon.spy()
    __RewireAPI__.__Rewire__('fancyFunc', spy)
    
    fancyDefault()

    expect(spy.called).to.be.true
  })
})

Also, check example: https://github.com/speedskater/babel-plugin-rewire#test-code-2



来源:https://stackoverflow.com/questions/45110688/how-to-spy-on-an-imported-function-using-sinon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!