r/react • • 9d ago

General Discussion Testing file sprawl

The last few projects I’ve worked on, I’ve implemented comprehensive testing (at least what I think is comprehensive). The problem is that I’m seeing just how many files and lines of tests it takes to be comprehensive.

I’ve been using jsdom and React Testing Library for these Vite TypeScript projects. Are there any alternatives that offer more shorthanded ways to do the same testing? One testing file per component/file seems unsustainable, but I also realize that less isn’t always more and “less” is arbitrary/subjctive.

If those are the gold standard, is there a way you organize your files that makes it more efficient/maintainable?

5 Upvotes

3 comments sorted by

3

u/LostTheBall 9d ago

You can have mirror tests folders, but I prefer to put a .test.tsx/.test.ts in the same folder with the same file name as the file you are testing

E.g. components/Dialog/Dialog.tsx components/Dialog/Dialog.test.tsx

You can group common groups of functionality within your test files under describe blocks, and can have more test files if really needed

It's ok and good to have a lot of tests - as long as they are meaningful (not checking 1 = 1, but something with functional purpose)

Vite also allows you to check coverage of your code base through npx cutest run --coverage

https://vitest.dev/guide/coverage

Watch out for:

  • Open handles, you can use --detect-async-leaks flag to look out for these

  • Not handling awaiting for/testing asynchronous events properly, you'll see a lot of not wrapped in act() spam when running tests when this happens

2

u/Affectionate_Use_164 8d ago

Just put test files in the same folder with component itself, same as guy bellow said. That "/tests" folder was repeated blindly from tutorials without thinking.

2

u/raks1991 4d ago

If several tests differ only in their input and expected message, Vitest's test.each puts those cases in a table. SignupForm here is made up; the snippet assumes RTL, user-event and jest-dom:

test.each([
  ['', 'Required'],
  ['abc', 'Enter a valid email'],
])('email %j shows %s', async (input, message) => {
  const user = userEvent.setup()
  render(<SignupForm initialEmail={input} />)
  await user.click(screen.getByRole('button', { name: 'Sign up' }))
  expect(await screen.findByText(message)).toBeInTheDocument()
})

For children that only exist inside one form, test the behavior through the form rather than giving every child its own file. Separate tests pay off for shared or logic-heavy pieces.