Reputation: 685
I've been having some issues when testing this component:
import React, { useState } from 'react';
import { BrowserRouter as Router, Link } from 'react-router-dom';
import styles from './Join.module.scss';
const Join = () => {
const [name, setName] = useState('');
const [room, setRoom] = useState('');
const handleChange = (e) => {
if (e.target.name === 'name') {
setName(e.target.value);
} else if (e.target.name === 'room') {
setRoom(e.target.value);
}
};
return (
<section className={styles.main}>
<h1 className={styles.main__title}>Join</h1>
<form className={styles.form}>
<label className={styles.form__label}>Name</label>
<input
className={styles.form__input}
name="name"
type="text"
onChange={handleChange}
/>
<label className={styles.form__label}>Room</label>
<input
className={styles.form__input}
name="room"
type="text"
onChange={handleChange}
/>
</form>
<Router>
<Link
onClick={(e) => (!name || !room ? e.preventDefault() : null)}
to={`/chat?name=${name}&room=${room}`}
>
<button className="btn btn--submit" type="submit">
Sign In
</button>
</Link>
</Router>
</section>
);
};
export default Join;
I want to simulate a change in the input name="name"
but the test keeps failing since the result is always ""
instead of foo
.
Can anyone explain to me what am I doing wrong? I've been searching for a solution with no luck.
Here's the test file:
import React from 'react';
import { mount } from 'enzyme';
import Join from '../Join';
describe('<Join />', () => {
let wrapper;
beforeEach(() => {
wrapper = mount(<Join />);
});
test('1- renders without errors and matches h1', () => {
const title = wrapper.find('h1');
expect(title.text()).toBe('Join');
});
test('2- name input', () => {
const name = wrapper.find('[name="name"]');
console.log(name.debug());
name.simulate('change', {
target: { value: 'foo' },
});
expect(name.text()).toBe('foo');
});
});
Thanks for your help!
Upvotes: 1
Views: 999
Reputation: 3373
Enzyme doesn't provide proper support for react hooks. https://enzymejs.github.io/enzyme/#react-hooks-support
You can use react-dom/test-utils along with enzyme. Example https://enzymejs.github.io/enzyme/#reacttestutilsact-wrap
But it is recommended to use React Testing Library for better support.
Upvotes: 2