how to mock saga generator function with jest and enzyme

3.3k Views Asked by At

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 :)

1

There are 1 best solutions below

0
On

check out this link to see example test of a saga: https://github.com/react-boilerplate/react-boilerplate/blob/master/app/containers/HomePage/tests/saga.test.js

What you want to do is test the saga generator function, in your case the signInFormSubmit...

You would import it as such as:

signInFormSubmitGenerator = signInFormSubmit();

Then you would want to assert things against the values returned at each 'yield' step.

However, I noticed that you have takeLatest within your generator function, which I don't believe is correct way to use it, its used to trigger other sagas (so it should be outside of the function, take a look here for example of well structured saga: https://github.com/react-boilerplate/react-boilerplate/blob/master/app/containers/HomePage/saga.js, notice how takeLatest is all the way at the bottom, and used as an entry point or a trigger for the generator function above it)