Joao Ramos
Joao Ramos

Reputation: 33

Passing props in a child component using jest mount

I am trying to build a small app to test my jest and enzyme knowledge. However, I have run into an issue.

I have the following Homepage.js:

const Homepage = props => {
    const [input, setInput] = React.useState({
        type: 'input',
        config: {
            required: true,
            placeholder: 'Type a GitHub username'
        },
        value: ''
    });
    
    const onChangeInput = event => {
        setInput(prevState => {
            return {
                ...prevState,
                value: event.target.value
            };
        });
    };
 
    return (
        <section className={styles.Homepage}>
            <form className={styles.SearchBox} onSubmit={(event) => props.getUser(event, input.value)} data-test="component-searchBox">
                <h4>Find a GitHub user</h4>
                <Input {...input} action={onChangeInput}/>
                {props.error ? <p>{`Error: ${props.error}`}</p> : null}
                <Button>Submit</Button>
            </form>
        </section>
    );
}; 

I want to test that the input field fires a function when I type in it. The Input.js component is the following:

const input = props => {
    switch (props.type) {
        case 'input':
            return <input className={styles.Input} {...props.config} value={props.value} onChange={props.action} data-test="component-input"/>
        default: return null;
    };
}; 

You can find my test below:

const mountSetup = () => {
    const mockGetUser = jest.fn()
    return mount(
        <Homepage type='input' getUser={mockGetUser}>
            <Input type='input'/>
        </Homepage>
    );
};
 
test('State updates with input box upon change', () => {
    const mockSetInput = jest.fn();
    React.useState = jest.fn(() => ["", mockSetInput]);
 
    const wrapper = mountSetup();
 
    const inputBox = findByTestAttr(wrapper, 'component-input');
 
    inputBox.simulate("change");
 
    expect(mockSetInput).toHaveBeenCalled();
});

The problem here is that in the Input.js the switch is always returning null even though I am passing the props type='input'. As such I get the error Method “simulate” is meant to be run on 1 node. 0 found instead.

Can someone help me with this?

Thanks

Upvotes: 0

Views: 2265

Answers (1)

vishnu sandhireddy
vishnu sandhireddy

Reputation: 1176

You need not pass the Input inside the HomePage. Homepage has input child and it renders

<Homepage type='input' getUser={mockGetUser}>
</Homepage>

You can try passing the data in the react Usestate mock.

React.useState = jest.fn(() => [{
  type: 'input'
}, mockSetInput]);

Upvotes: 2

Related Questions