【问题标题】:React + Redux - Call a method of a component wrapped for the Redux ProviderReact + Redux - 调用为 Redux Provider 包装的组件的方法
【发布时间】:2018-07-03 13:25:34
【问题描述】:

怎么了,

我正在尝试测试一些使用 redux 的 react 组件。

默认行为应通过休息调用加载选择输入中的选项列表。此调用是在我的组件中的方法 componentDidMount() 上进行的。

该组件工作正常,但我无法在测试中模拟相同的行为。

我无法从由 Provider 包装的实例调用方法 componentDidMount()。

谁能帮我解决这个问题

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

import { reducer as formReducer } from 'redux-form'
import { createStore, combineReducers } from 'redux'
import { Provider } from 'react-redux'

import ConnectedComponent from '../../../src/components/Component'

describe('Component <Component />', () => {
    let store = createStore(combineReducers({ form: formReducer }))
    let wrapper = mount(<Provider store={store}><ConnectedComponent /></Provider>)

    // this call does not works
    wrapper.instance().componentDidMount()

    it('should load select input on component mount', () => {
        expect(wrapper.find('select option')).to.have.length(12)
    })
})

【问题讨论】:

  • 不应该mount 为你这样做吗?为什么要直接调用生命周期方法?

标签: reactjs redux tdd provider


【解决方案1】:

我能够做到以下几点:

import React from 'react';
import {connect} from "react-redux";

export class Mock extends React.Component {
    constructor(props) {
        super(props);
    }
    myMethod() {
        return 123
    }
    render() {
        return (
            <div>Test</div>
        )
    }
}

Mock = connect()(Mock);

export default Mock;

笑话测试sn-p:

const wrapper = mount(
    <Provider store={store}>
        <Mock/>
    </Provider>
)
let result = wrapper.find(Mock).children().instance().myMethod();
expect(result).toEqual(123);

希望对某人有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-22
    • 2019-12-02
    • 2019-05-03
    • 1970-01-01
    • 2023-02-24
    • 2021-12-24
    • 2021-06-23
    • 1970-01-01
    相关资源
    最近更新 更多