11

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.

Marc
  • 2,900
  • 3
  • 26
  • 40

2 Answers2

11

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
  })
})
Yoav Kadosh
  • 4,807
  • 4
  • 39
  • 56
Sebastian
  • 301
  • 3
  • 4
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

Yoav Kadosh
  • 4,807
  • 4
  • 39
  • 56
Alexey Kucherenko
  • 885
  • 1
  • 8
  • 11