vendredi 29 juillet 2016

Confusion with mocking stateless React component helper functions with sinon, enyzme, and ES6 imports

I'm currently trying to unit test a React component and have run into some confusion about mocking functions the helper functions. The module looks something like this

export const someHelper = () => {
  return ( <div></div> )
}

const MyComponent = () => {
  return (
    <span>
      {someHelper()}
    </span>
  )
}
export default MyComponent

and then this is what the test file looks like

import chai, { expect } from 'chai'
import chaiEnzyme from 'chai-enzyme'
import sinon from 'sinon'
import { shallow } from 'enzyme'
import React from 'react'

import MyComponent, { someHelper } from './MyComponent'

describe('MyComponent test', function (){
  it.only('should call someHelper once', function () {
    let spy = sinon.spy(someHelper)
    let myComponent = shallow(
      <MyComponent />
    )
    expect(spy.callCount).to.equal(1)
  })
})

This test fails however as callCount equals 0. I figured that maybe it had something to do with the context of the someHelper function, so I made these changes

export const helpers = {
  someHelper () {
    ...
  }
}
const MyComponent = () => {
   ...
   {helpers.someHelper()}
   ...
}

_

import MyComponent, { helpers } ...

describe(...{
  it(...{
    let spy = sinon.spy(helpers.someHelper)
     ...
  })
})

But this test still fails with callCount equaling 0. I then made these changes

describe(...{
  it(...{
    let spy = sinon.spy(helpers, 'someHelper')
     ...
  })
})

And then test now passes.

Why do I have to attach someHelper to the helpers object for this test to work? And why do I have to use that last spy(object, 'myfunc') method when the sinon docs show a spy(myFunc) option?

Aucun commentaire:

Enregistrer un commentaire