【问题标题】:React: How to test component's input which uses ref?React:如何测试使用 ref 的组件输入?
【发布时间】:2019-11-27 11:21:07
【问题描述】:

我有一个用于搜索主题的组件:

class Search extends React.Component {
    constructor(props) {
        super(props);

        this.subjectNameInput = React.createRef();
        this.searchSubjectsByName = this.searchSubjectsByName.bind(this);
    }

    searchSubjectsByName(e) {
        console.log("INPUT", this.subjectNameInput.current.value); <--- empty value
        console.log("INPUT", e.target.value); <--- correct value
        this.props.searchSubjectsByName(this.subjectNameInput.current.value);
    }

    render() {
        return (
            <div className="input-group mb-3">
                <div className="input-group-prepend">
                    <span className="input-group-text" id="basic-addon1">Search</span>
                </div>
                <input onChange={(e) => this.searchSubjectsByName(e)} ref={this.subjectNameInput} type="text" className="form-control" placeholder="Subject name" aria-label="subject"
                       aria-describedby="basic-addon1"/>
            </div>
        )
    }
}

const mapDispatchToProps = (dispatch) => ({
    searchSubjectsByName(pattern) {
        dispatch(searchSubjectsByName(pattern))
    }
});

const SearchContainer = connect(null, mapDispatchToProps)(Search);

export default SearchContainer;

我有一些测试:

describe("Search component spec", () => {
    const middlewares = [thunk];
    const mockStore = configureStore(middlewares);

    ...

    it('emit SEARCH_SUBJECTS_BY_NAME event', () => {
        const expectedActions = [
            {type: types.SEARCH_SUBJECTS_BY_NAME, pattern: 'sample'},
        ];

        const store = mockStore();
        const wrapper = mount(<Provider store={store}><SearchContainer/></Provider>);
        wrapper.find('input').simulate('change', {target: {value: 'sample'}});
        expect(store.getActions()).toEqual(expectedActions)
    });
});

当模拟动作change 时,我从this.subjectNameInput.current.value 得到一个空值,但如果我尝试不是从ref 而是从事件的目标e.target.value 获取值,那么我会得到正确的值。

如何为使用 refs 作为输入的组件正确编写测试?

【问题讨论】:

    标签: javascript reactjs testing jestjs


    【解决方案1】:

    似乎要更改 react 的 ref 需要使用 getDOMNode().value = ... 并在此之后模拟操作。

    it('emit SEARCH_SUBJECTS_BY_NAME event', () => {
        const expectedActions = [
            {type: types.SEARCH_SUBJECTS_BY_NAME, pattern: 'sample'},
        ];
    
        const store = mockStore();
        const wrapper = mount(<Provider store={store}><SearchContainer/></Provider>);
        const input = wrapper.find('input');
    
        input.getDOMNode().value = 'sample';
        input.simulate('change');
    
        expect(store.getActions()).toEqual(expectedActions)
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-05
      • 2021-10-24
      • 1970-01-01
      • 2018-04-06
      • 1970-01-01
      • 2018-06-13
      • 1970-01-01
      • 2019-03-23
      相关资源
      最近更新 更多