在Jest中模拟异步动作创建者

时间:2017-10-15 16:40:06

标签: reactjs unit-testing redux jestjs

我从反应容器中的export class MainContainer extends Component { render() { const { props } = this const { isFetching, userInfo } = props return ( isFetching ? <Loading pageName={'Home Page'} /> : <div> {userInfo && <div> <p>{`Name : ${userInfo.name}`}</p> <p>{`Email : ${userInfo.email}`}</p> </div> } </div> ) } componentDidMount() { const { props } = this const { userLogin } = props // This is an async action creator, came in props by // `mapDispatchToProps` userLogin() } } /** * Maps dispatch and action ceators to render method * @param {function} dispatch store's dispatch method * @return {object} action creators in object */ function mapDispatchToProps(dispatch) { // userActionCreators has userLogin method return bindActionCreators(userActionCreators, dispatch) } function mapStateToProps({ user }) { const { isFetching, error, userInfo } = user return { userInfo, isFetching, error } } export default connect(mapStateToProps, mapDispatchToProps)(MainContainer) 处获取API中的一些数据,这就是代码结构的方式:

TypeError: userLogin is not a function

我最近开始在我的代码中添加单元测试,我正在使用Jest和Enzyme。当我运行测试时,我收到此错误:

userLogin

我知道我需要模拟import React from 'react' import renderer from 'react-test-renderer' import configureStore from 'redux-mock-store' import { shallow } from 'enzyme' import { initialState } from '$REDUX/modules/user' import ConnectedMainContainer, { MainContainer } from './MainContainer' // Snapshot matching for Main Container describe('MainContainer Snapshot', () => { const mockStore = configureStore() let store, container beforeEach(() => { store = mockStore(initialState) container = shallow(<MainContainer store={store} />) }) it('Matches the snapshot', () => { const tree = renderer.create(<MainContainer />).toJSON() expect(tree).toMatchSnapshot(); }) }) // ************************************************************* 函数,但我不知道如何将它传递给测试文件中的容器。这是我的测试文件的外观:

{{1}}

请让我知道我在这里失踪了什么。

1 个答案:

答案 0 :(得分:1)

最简单的方法是在shallow调用中传递它。

describe('MainContainer Snapshot', () => {
  const mockStore = configureStore()
  let store, container, userLogin

  beforeEach(() => {
    userLogin = jest.fn()
    store = mockStore(initialState)
    container = shallow(<MainContainer store={store} userLogin={userLogin} />)
  })

  it('Matches the snapshot', () => {
    expect(container).toMatchSnapshot();
  })

  it('logs in the user', () => {
    expect(userLogin).toHaveBeenCalled();
  })

})