ueeieiie
ueeieiie

Reputation: 1562

How to set a value to an input text element of a stateless function inside a Jest test

Since Im using a stateless function I cannot use this:

wrapper.find('input').instance().value = 'some text'

this also is depreacted:

wrapper.find('input').node.value = 'some text'

Do you know what would be a proper way of achiving this ? I'm little new to tests, so correct me if I'm wrong:

  1. I created the component with const component = mount(<PostMessages/>).

  2. I targeted the text input like this: const input = component.find('input').

  3. this is my missing peace.

my Component:

const PostMessage = props => {
    let inputText;

    const onKeypressHandler = (e) => {
        if (e.key === 'Enter') {
            if (inputText.value) {
                sendMessage(inputText.value);
                clearInput();
            }
        }
    }

    const clearInput = () => {
        inputText.value = '';
    }

    const setRef = (input) => {
        if (input) {
            inputText = input;
            inputText.focus();
        }
    }

    const stringIsBlank = (str) => {
        return (!str || /^\s*$/.test(str));
    }

    const formatMessage = (message) => {
        return stringIsBlank(message) ? false : message.trim();
    }

    const sendMessage = (message) => {
        const formatedMessage = formatMessage(message);

        if(formatedMessage) {
            props.send(formatedMessage);
        }
    }

    return (
        <PostMessageStyle>
            <input type="text"
                placeholder="Your message..."
                onKeyPress={onKeypressHandler}
                ref={input => setRef(input)}
            />
            <button onClick={sendMessage}>Send</button>
        </PostMessageStyle>
    )
};

Upvotes: 1

Views: 1155

Answers (1)

Vincent D&#39;amour
Vincent D&#39;amour

Reputation: 3903

You correct doing wrapper.find('input').instance().value = 'some text' but you also need to trigger the change event on the input. You can do it like so:

const myInput = wrapper.find('input');
myInput.instance().value = 'some text';
myInput.simulate('change');

Or you can also directly trigger the change event with the value like this:

wrapper.find('input').simulate('change', { target: { value: 'some text' } });  

This will only work for component, not function. There is no way of doing that because stateless components don't have methods. From the creator of the librairy:

The answer is you don't test that function - you only test Component, and you add tests for all the code paths. You can't test that directly, and shouldn't.

If you want to test it, you have to convert it into a component.

Upvotes: 1

Related Questions