3

我正在尝试测试当我调用调度函数时是否调用了我的生成器函数。我正在做类似的事情:

在我的 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
  })
}

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

在我的 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)
  }
})

我认为我的问题是我必须模拟我作为参数传递给 takeLatest 的生成器函数。我尝试了很多东西,但没有奏效。结果显示“我在”

谢谢大家帮助 :)

4

1 回答 1

1

查看此链接以查看 saga 的示例测试:https ://github.com/react-boilerplate/react-boilerplate/blob/master/app/containers/HomePage/tests/saga.test.js

您想要做的是测试传奇生成器功能,在您的情况下是 signInFormSubmit ...

您可以将其导入,例如:

signInFormSubmitGenerator = signInFormSubmit();

然后,您可能希望针对每个“产量”步骤返回的值进行断言。

但是,我注意到您的生成器函数中有 takeLatest,我不认为这是使用它的正确方法,它用于触发其他 saga(所以它应该在函数之外,请看这里的例子结构化 saga:https ://github.com/react-boilerplate/react-boilerplate/blob/master/app/containers/HomePage/saga.js ,注意 takeLatest 一直在底部,并用作入口点或它上面的生成器函数的触发器)

于 2018-10-05T14:30:01.447 回答