dimanche 23 septembre 2018

how to mock saga generator function with jest and enzyme

I'm trying to test if my generator function is called when I call dispatch function. I'm doing something like:

in my saga.js:

import { takeLatest } from 'redux-saga/effects'

import { SIGNIN_FORM_SUBMIT } from './constants'

export default function* signInFormSubmit() {
  return yield takeLatest([SIGNIN_FORM_SUBMIT], function*() {
      console.log("I'm in")
      return yield null
  })
}

in Form.js:

import React, { Component } from 'react'
import { connect } from 'react-redux'

import { SIGNIN_FORM_SUBMIT } from '../constants'

class SignInForm extends Component {
  handleSubmit = this.handleSubmit.bind(this)
  handleSubmit() {
    this.props.dispatch({
      type: SIGNIN_FORM_SUBMIT
    })
  }

  render() {
    return (
      <div>
        <button onClick={() => this.handleSubmit()}>Submit</button>
      </div>
    )
  }
}

export default connect()(SignInForm)

in my test.js:

import React from 'react'
import configureStore from 'redux-mock-store'
import createSagaMiddleware from 'redux-saga'
import { Provider } from 'react-redux'
import { mount } from 'enzyme'

import signInFormSubmitSaga from '../saga'
import SignInForm from '../components/Form'


const sagaMiddleware = createSagaMiddleware()
const mockStore = configureStore([sagaMiddleware])
const store = mockStore()
sagaMiddleware.run(signInFormSubmitSaga)

describe('<Form />', () => {
  test('should call signInFormSubmit saga when I click on the sumbit button', () => {
      const wrapper = mount(
          <Provider store={store}>
             <SignInForm />
          </Provider>
      )

       wrapper.find('button')
      .simulate('click')

      // I'm blocked here
      // expect(...).toHaveBeenCalledTimes(1)
  }
})

I think my problem is that I have to mock the generator function that I pass as params to takeLatest. I tried lot of things but it didn't work. The result show well "I'm in"

Thanks guys for your help :)

Aucun commentaire:

Enregistrer un commentaire