We’ve already talked about what testing is and why you should learn it here, but now let’s explore how testing actually works. I like to think of testing as taking the code we’ve written and using more code to ensure that it works. Simply put, we are simulating our application’s behaviour using code and ensuring that it behaves how we expect it to.
Below are a few examples of different testing scenarios using variables, functions, and React components
For example: here’s a simple test where we assert the values of the variables “a” and “b”.
The great part of testing is that a lot of the code reads like English! Here we’ve defined “a” to the value of 2 and “b” to the value of 3, which says that we “expect” a variable “to be” a certain value. Our test expectation is that we can expect “a” to be 2 and “b” to be 3. Since that is true our tests pass - hurray!
Now you might be thinking “Well duh!” that’s so obvious - but this is just a simple example. Taking it to the next step we might do something like this:
Now we’re asserting the result of an expression. That we expect a + b (2 + 3) to be 5. Which is true. Suppose I’m refactoring my application and for some reason I decide that I need to change the variable b to equal 2:
Now our test actually fails! This is great because we can see where our test is failing. We expected to receive a value of 5 and our current values for “a” and “b” only add up to 4. Knowing exactly where I broke my code makes it much simpler for me to find a solution.
This is a simple example, but as I mentioned before when you get into a large enterprise level application with thousands of lines of code, much more complicated things can break - and they do!
If we have a file that contains all of our constant variables and we decide to change one to suit file A it might end up breaking file B where the variable occurs again. Our application might start behaving differently if we do, or in the worst case - we might not even notice the change at all, and our application would push to production with the error. With a full test suite, we’d likely be able to catch any changes in our application’s behaviour and, more importantly, we’d know where the breakages were happening.
One of the main test runners that many developers use is called jest. The methods I used here all come from the jest API, such as:
test() toBe() expect()
If you are interested you can find more about Jest here.
Trying to comb through thousands of lines of code to find where it is breaking can be a chore and testing helps us minimize the number of errors and bugs we introduce into an application. In short, testing will give you confidence in your code.
Ready to learn React Testing and how to apply other helpful tools like Hooks in your own code? You can book a call with a member of our Student Success Team now to get started.