I'm currently writing a test for a simple form:
export const TestComponent = () => {
const [todos, setTodos] = useState([`Todo 1`, `Todooo 2`]);
const todoInputRef = useRef<HTMLInputElement>(null);
return (
<div className={style.wrapper}>
<div className={style.todos}>
<div className={style.todoList}>
{todos.map((current, i) => (
<div className={style.todo} key={`todo-` + i}>
<span>{current}</span>
</div>
))}
</div>
<div className={style.addTodo}>
<input
ref={todoInputRef}
className={style.todoInput}
type="text"
placeholder="Type a todo here ..."
/>
<button
onClick={() => {
act(() => {
const currentTodoInputRef = todoInputRef.current;
if (currentTodoInputRef) {
console.log(currentTodoInputRef);
setTodos(todos.concat(currentTodoInputRef.value));
}
});
}}
type="submit"
>
OK
</button>
</div>
</div>
</div>
);
};
As you see I have a console.log in the onClick-event of the Button. My problem is, that I'm getting a different ref when I call the event via enzyme.
Ref when I click the button manually: {current: input.TestComponent_todoInput}
When enzyme triggers the event: {current: WrapperComponent {...}}
So how can I get the "real" ref?
In the test code I'm giving the input a value and then I click the button. But the new listitem is always just an empty string because the event of the button click can't read the ref.
My test code:
let wrapper: ShallowWrapper;
beforeEach(() => {
wrapper = shallow(<TestComponent />);
});
it(`add todo works`, () => {
const form = mount(
wrapper
.find(`div.todos`)
.find(`div.addTodo`)
.getElement()
);
const input = mount(form.find(`input`).getElement());
input.props().value = `xyz`;
const button = form.find(`button`);
button.simulate(`click`);
});
Thank you for your help.
Kind Regards Luca
Aucun commentaire:
Enregistrer un commentaire