1

so I had written a sample test case for an input, where if I press enter it clears the input field. It works till this point, but when I try to type after that, somehow the previously typed text comes back as part of the input value, and it's driving me crazy.

I have tested this visually, and it works perfectly fine visually (same props and all), so it does not make sense for the test to behave this way. I'm using jest, react-testing-library and user events. Attaching a minimal reproducible test with comments to explain what the test says.

it('reproducible issue', async () => {
    const { findByLabelText } = renderWithChakraProvider(
      <TagInput label="tag-input" id="tag-input" name="tag-input" />
    );

    const inputElement = await findByLabelText('tag-input');

    await userEvents.type(inputElement, 'test 1');
    expect(inputElement).toHaveValue('test 1'); // passing

    await userEvents.type(inputElement, '{enter}'); // this presses the enter/return key on the input field
    expect(inputElement).toHaveValue(''); // passing, this should mean input has been cleared

    await userEvents.type(inputElement, 'test 2');
    expect(inputElement).toHaveValue('test 2'); // FAILING, it expects `test 1test 2`, HOW is `test 1` value coming back after having been apparently cleared????
  });

I know I can probably just run clear() after asserting that the value is empty, but any idea why it is behaving like this?

lanxion
  • 1,350
  • 1
  • 7
  • 20
  • I did a simple test with an `input` base Element and all work as expected. So the problem could be in your `TagInput` or some related to chakra library (I would go with `TagInput`). If you also add the component code we can try to check it out. – Luis Paulo Pinto Jun 16 '22 at 00:01
  • a regular input component is not supposed to clear the data in the field. How exactly are you testing this? Moreover, as I mentioned, I have tested this visually in storybook and is working as intended, but the test is not reflecting it. Lastly, it is working as expected up until the 2nd last testcase, where it is confirming that input value is empty, then after typing new text, somehow old text is reappearing, how is that even supposed to be possible? – lanxion Jun 16 '22 at 11:41
  • I just created a controlled input component and added a code to clear it on `enter` click. And it works with the flow -> `Test 1` -> `{Enter}` -> `Test 2`. At the end of the test the input has only `Test 2`. That´s how i test it. – Luis Paulo Pinto Jun 16 '22 at 12:57
  • I see, my component is uncontrolled and I have to force an onChange event – lanxion Jun 16 '22 at 15:20

0 Answers0