Testing and formatting in React - a school project
Published: 2021-02-19 13:16:26

# What's good to know about testing and formating

The first thing that we are gonna talk about is:

- How to make tests of a component in a texteditor using react testing library
- in that case we can ask ourself why it's a good idea to make tests in the first place. Its not something that our viewers can se and it takes more time to do it!

So why do we do it?

We do it so we can make sure that our code are doing what it is meant to do. Therefore we can push, commit and deploy being sure the code behaves the way it should behave. Its called `TDD` - which stands for `test driven design`.

And that leads me to my next point

## How do we do it?

1.  First and foremost we have to make a new file. If you wanna test a component called `foodcorner.js` for example you have to name the testing file `foodcorner.test.js` - so the testing file must have the same name as your component, just add the test part before js.
2.  The next part is the actual code part.
    before we go any further its important to mention that there are different things you have to write - depending on what your code does - for example if you use axios/fetch in your component you have to do some more, than if its just returns a text for example.

- so lets try to see a simple test of an component that only returns some hardcoded text

I have made a component that returns an a href with some text - so it look like this: 
```javascript
export default function Header() {
    return (
        <a href="/" className="Brand"> my app</a>
    )
}
```




In this first case the component is called header.js and we want to make a test of this component

1.  First we make a file called header.test.js and you can put it in src with your component
2. the second thing is to add some code - we open our test file and start coding.

3.  first we have to import render and screen from the testlibrary and ofcourse our component - so -
```javascript 
import { render, screen} from "@testing-library-react";
import Header from "./header"
```


4.  Then we need to write some code

```javascript 
test("Check if Header renders with my app text", function(){
    render(<Header/>)
    var BrandText = screen.getByText(/my app/i);
    expect(Brandtext).toBeinTheDocument()
})
```




5.  so what is hapening here? first we need to import our thing so we have acces to them
6.  second we have to define our test and a callback function that render our component. in our function we make a variable where we get acces to the screen and uses getByText from the library APi to get the text. Finaly we expect to have the word my app in the document, which we defines in the regular expression with (/my app/). The i after, is to make sure that it is not case incesetive.

### But did you remember i said that you had to do something else if you compoenent have an axios call? Lets have a look




In this case i also have an example - i have made a file called `pokemon.js` and i use an axios call to the pokemon API. 

1. first we make our test file(just like in the example above) and then we do our imports, but we need som more this time. we need five functions from our testing-libaray

act, screen, cleanup, render, waitfor and ofcourse our component, axios and mockedAxios


lets see how all the code looks and after we look what happens:

```javascript
import { act, screen, cleanup, render, waifor } from "@testing-library/react";
import Pokemon from "/pokemon"
import mockedAxios from "axios"
import axios from "axios"

afterEach(cleanup)

jest.mock("axios")

test("Test if pokemon works with axios", async function () {
 var response = {
  data: {
   resuts: [
        {
     name: "bulbasaur"
    },
    {
     name: "pikachu"
    },
   ],
  },
};
    mockedAxios.get.mockResolvedValue(response)
    act(function(){
        var text = screen.getByText(/bulbasaur/i)
        expect(text).toBeinTheDocument()
    })

});
```



In order for this to work we also have to make a new folder called `__mocks__`. In that folder we make a new file called `axios.js` - where we write -

 ```javascript 
get: jest.fn().mockResolvedValue,
post: jest.fn()mockResolvedValue,
```

now we have everything that we need:D so lets take us some time to see whats going on:D

first we have our `afterEach(cleanup)`, this sentence are onmounting the pokemoncomponent after every test, its like a cleanup

`jest.mock("axios")` here we tell jest(which is the name of the testing library) to use a mock of axios which you can find in the `__mocs__`folder.

`test("Test if pokemon works with axios", async function(){` : on this line we defines a test which is a description of our test and a async function. Axios is a async function



`mockedAxios.get.mockResolvedValue(response)` : here we are telling jest to use the response above instead of the real one

`act(function(){` : because our components has an async function we have to wait for the function to finish

 render(<Pokemon />); : next we render our pokemon conponent
  });
  await waitFor(function () { : we use waitfor to wait for the async function
    var text = screen.getByText(/bulbasaur/i);
    expect(text).toBeInTheDocument(); : here we have something we have seen before 
  });
});





you can also make something called `pre-hooks test`. For that you need something called `husky`. you write `npx husky install` in the editor-terminal. there will now be created a new folder called `.husky` - now you can write `npx husky add .husky/pre-commit "npm test`


## So this was the testing part. Now i would like to talk about something called `prettier` - prettier is an npm package that formats your code

1. first we install prettier - npm i prettier and eslint-config-prettier as a devdependency - npm i -D eslint-config-prettier.
2. go to yor package.json and make a new script called prettier. this command should run prettier --write

so it would look like this :
```javascript
"prettier": "--write"
``` 



3. we have to make a file called `pretterirc.json` where we will write what prittier should do - it could look like this {

```javascript
   "printwidth": 120,
   "use-tabs": true,
   "semi": true,
   "singleQuete": false,
   "qoteProps": "consistent",
   "bracketSpacing": true
   }   

to take some examples we tell prettier to make a line break if its over 120 if it can. we also tells it to use tabs instead of spaces and to have bracketspacing - there are ofcourse many more properties to add. if you find that interesting you can visit the documentation:D

An good idea is also to make a `.prettierignore` file to tell what prettier should ignore:D 

And now you can just write `npm run test` and you can see in your code that prettier has made some changes:D

prettier also has something called pre-commit hooks and that means that our code will be formated automatecly right before we commit our code - and the comand we are using for that is something called `lint-staged`(an important thing to know here is that prettier has to be `installed as an devdependency`). You can either install it as a devdependency or simply just move it in your package.json:D

next step is to write `npx mrm lint-staged` - this will install husky and lint-staged.

and you now stage and commit - but before you commit, prettier will format your code and that means you can now push with confidence. 

Yay:D