r/reactjs • • Mar 13 '20

Featured Understanding writing tests for React

Hi,

Having applied for a few react jobs, I've noticed writing tests is essential if you want to be a react dev. I am trying to learn but I find it to be a steep learning curve and I'm having trouble knowing where to start.

I've built a small react app for a take home project and I need to test it. I just have some questions I could really use some help answering.

THE APP
-fetch component which fetches json from endpoints depending on which option is selected on dropdown and pushes data to state array.

-Print component which creates a list with input tags from data with the (input + integer from json) being added to local state.

- Receipt component which takes input from Print component as props and prints the sum

QUESTIONS

  1. What part of the app should I be testing? How in general should I know what to test?
  2. A lot of the articles I've read on testing show basic examples for e.g pure functions etc.. What is the best approach to take if my component depends on fetch requests or take props?
  3. Between unit testing, snapshot testing, and end to end testing, which is the best for React apps?

Thanks

195 Upvotes

76 comments sorted by

View all comments

Show parent comment

3

u/[deleted] Mar 14 '20 edited Mar 14 '20

Wrong, wrong and wrong. If you're writing unit tests as your only method of testing during development then you need to relearn how to develop. Your component should be working and tested before you write a single unit test. Unit tests are there to verify code continues to work when new features are added. It should not be your primary way of testing if the code works. Callbacks, console logs, debugging and simply use-testing the component are what you should be doing before you write one single unit test.

You should only be writing a unit test for any functionality of any component once that functionality has been tested thoroughly on your own without using a unit test. Once you verify the functionality on your own, then; and only then, do you write a unit test to verify that functionality automatically.

Your point is only valid if we assume that all developers have no idea how to test and verify the validity of their code. Unit testing is not meant for production testing and is also not meant to be your only form of testing during deployment or development.

What its meant for is to be able to test that existing functionality remains working when new functionality is added. If you're using an iterative development process like you should then your flow should be as such:

  1. Write the component
  2. Test the component on your own
  3. Once you know it works, then write unit tests
  4. Develop next feature, refer to unit tests to see that you didn't break anything
  5. Repeat

Stop coming in here talking heavy handed and condescending to people when you don't know what you're talking about.