Jest
What is it
- It is a Javascript test framework.
- Can be used both in front-end and back-end, but its commonly used on the backend.
- Can be used with: React, Node, React Native, and many others.
- Developed by Facebook.
How to use
- Install
Jest
globally in your computer usingnpm install jest --global
. - Go to your project root and run
npm install --save-dev jest
. - Create a folder in the root named as
__tests__
. - Then, initialize the
Jest
configuration file withjest --init
.At the root will appers a new file
jest.config.js
. ( Access this link to understand about each configuration )
Writing tests
At this point, the environment is already set, so now we can write the tests.
Now we need to create a file inside
__tests__
folder, in my caseexample.test.js
.Obs: Isn
t required to end the filename with
.test.js(can be just
.js`), but it is interesting to keep the code well organized.// 'it' can be traded for 'test' it("two plus two is four", () => { expect(2 + 2).toBe(4); });
As you can see, with this simple way we can write trivial tests and complex one, for example, asynchronous code:
// 'it' can be traded for 'test' it("two plus two is four", async () => { try { const data = await fetchSomeData(); //...// } catch (e) { expect(e).toMatch("error"); } });
In some cases, one test file can have multiple features to be tested, then we can use the
describe()
to 'split' the tests into categories:# __tests__/session.test.js describe('Authorization', () => { it('should authenticate with valid credentials', () => { //Some logic }); it('should not authenticate with invalid credentials', () => { //Some logic }); }); describe('Registration', () => { it('should add an user in database', () => { //Some logic }); it('should not add an user in database ', () => { //Some logic }); });
Running tests
To run the test simply, you can just add a script at
package.json
named astest
.... "scripts": { "test": "jest", }, ...
Then, in your terminal run
npm run test
. And finally tests is working!
Learning more
Useful content
- As always the oficial docs are a great place to get more info.
- Video About
NodeJs + Jest + TDD
. (Turn on the english subtitle)
Validating knowledge
- It is always very important to put into practice what you learn, to solidify and validate de knowledge. So we strongly recommend you tom start a project and put the hands on.
- Think about something simple, like login + authentication, o some like this.