First Steps towards React Testing ( Jest Edition )

First Steps towards React Testing ( Jest Edition )

Backdrop

I was always afraid of testing as I never understood how can someone test the UI and was always intimidated by it, but I was cornered into a situation where I need to write test for my component so finally I decided to face my fear and learn some testing.

I have followed this amazing course and learnt some basic testing techniques, this blog will be a summary of that course and will enable you to start writing tests for your components.

Jest

Getting Started

[Jest] [jestjs.io/docs/getting-started] is a JS framework that is used for creating test, its very simple to use. So let's start by installing it.

npm install --save-dev jest
  • Also create a__tests__ directory inside your source folder

Pasted image 20221117231053.png

  • add this script inside your pacakge.json, it will run jest command when you do "npm run test" jest __tests__/ --coverage

Pasted image 20221117230647.png

  • coverage flag will provide us the detailed report of our test like this

Pasted image 20221117230939.png

Writing our tests

Gathering Requirements :

  • Before writing tests we should be aware about the functions or logic of our component, let's take an eg
  • we have a component "receipe.js" it has these functions:
    • findRecipe("pesto") -> takes a receipe name as input -> fetch the api and provide receipe in response
    • getIngredients(receipe) -> converts receipe object into list of ingredients

Pasted image 20221120232806.png

Unit Testing:

  • In jest we can write test by simply creating a test function:
  • Test function takes 3 arguments:
    • Name of the test
    • Callback function that contains a testing logic
    • (optional) Timeout: to wait for the test before aborting, default is 5000ms
    • e.g.

Pasted image 20221120233549.png

Assert functions
  • Jest provides us some asset functions, that we can use to tell what output we want from our functions
  • expect() is an asset function, we can use it like this,
  • expect(2+2).toBe(4)
    
  • they take expression as input and are used in conjunction with matcher functions

Matcher functions
  • functions like toBe() are used to validate the output assert functions, if they found the values of the expect and matcher to be different then test will fail `

Arrange, Act, Assert Pattern

To write good tests we follow this pattern,

  • Arrange: Firstly we arrange the input that we're going to pass into function and also the expected output we will get from the function
  • for e.g in findIngredients
  • // arrange 
    
    const pestoRecipe = {  
      'Basil': '2 cups',  
      'Pine Nuts': '2 tablespoons',  
      'Garlic': '2 cloves',  
      'Olive Oil': '0.5 cups',  
      'Grated Parmesan': '0.5 cups'  
    }  
    const expectedIngredients = ["Basil", "Pine Nuts", "Garlic", "Olive Oil", "Grated Parmesan"]
    
    • Act : Then we run our main function and pass the pestoReceipe as input
    • const actualIngredients = getIngredients(pestoRecipe);
  • Assert: Finally we use assertions to test whether the expected output and the actual output is same or not

  • expect(actualIngredients).toEqual(expectedIngredients)

  • In this way we have completed writing tests for our findIngredients function

// import the function to test  
import { getIngredients } from "./recipes.js";  

test("Get only the ingredients list for Pesto", () => {  
  //arrange  
  const pestoRecipe = {  
    'Basil': '2 cups',  
    'Pine Nuts': '2 tablespoons',  
    'Garlic': '2 cloves',  
    'Olive Oil': '0.5 cups',  
    'Grated Parmesan': '0.5 cups'  
  }  
  const expectedIngredients = ["Basil", "Pine Nuts", "Garlic", "Olive Oil", "Grated Parmesan"]  

  //act  
  const actualIngredients = getIngredients(pestoRecipe);  

  //assertions  
  expect(actualIngredients).toEqual(expectedIngredients)  
});

Conclusion

This is how a basic test logic is written, I tried to summarize the course so that anyone can get started with testing easily and overcome there fear for testing but there's more to testing, feel free to explore the course and here's the cheatsheet of the course for your reference.