0

I have a form with two inputs. one is textbox the other one is material ui autocomplete. I am using Yup to validate them. If any of them is empty then error text appears. They are empty as default. In initial render there are two errors expectedly. However, when I fill the inputs (one by typing, the other one by selecting), errors messages become 1. But should 0 since two of them is filled.

    const title = screen.getByRole('textbox', {name: 'title'})
    const kind = screen.getByRole('textbox', {name: 'kind'})
    const errors = await screen.findAllByText('Can not be blank!')
    expect(errors).toHaveLength(2)

    userEvent.type(title, 'abc')
    userEvent.click(kind)
    const menuItem = await screen.findByText('first option')
    userEvent.click(menuItem)
    const newErrors = screen.queryAllByText('Can not be blank!')
    await waitFor(() => expect(newErrors).toHaveLength(0))

The remaining error is related to kind right now. However, if I comment kind, there are two errors. If I comment title, there are still 2 errors. So this made me think that maybe this is a problem with async. so I used await and waitFor in almost everywhere but did not work. What is the problem here?

Burak Gündüz
  • 466
  • 5
  • 11
  • Did you try and wait for `newErrors` instead? `const newErrors = await screen.findAllByText('Can not be blank!'); expect(newErrors).toHaveLength(0);` – lbsn Sep 14 '21 at 08:51
  • Yes, unfortunately, I still have 1 error instead of 0 – Burak Gündüz Sep 14 '21 at 09:08
  • Might be something related to your component implementation? Could you share the component code, possibly yup validation as well? – lbsn Sep 14 '21 at 09:45
  • Actually I can not, sorry. But thanks for the help. I solved it, you can see my solution below. – Burak Gündüz Sep 14 '21 at 10:12

1 Answers1

1

The thing is instead of trying to get new errors and asserting on that variable, after the userEvent.click(menuItem), I used waitForElementToBeRemoved method to assert whether elements are removed or not as below:

await waitForElementToBeRemoved(() =>
      screen.queryAllByText('Can not be blank!')
    )

Since this method throws an error if element(s) are not removed and my tests are currently passing, I think it worked!

Burak Gündüz
  • 466
  • 5
  • 11