mercredi 27 novembre 2019

React: How to test component's input which uses ref?

I have a component which is used for searching subjects:

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;

And i have some tests for it:

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)
    });
});

When action change is simulated i get an empty value from this.subjectNameInput.current.value, but if i try to get value not from ref, but from event's target e.target.value then i get the correct value.

How to correctly write tests for components which use refs for inputs?

Aucun commentaire:

Enregistrer un commentaire