DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,673 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for How can i config tests in nodejs api with jest
Siqueira
Siqueira

Posted on • Updated on

How can i config tests in nodejs api with jest

Before we start the config we need to now some things:

Why test my app? πŸ€”

To make your service scalable, and more consistent!

What is jest? πŸ’­

Because is the most complete and easy to use!

First of all you need to installing the packages below on your project:

  • Jest the test framework:
  yarn add jest -D
Enter fullscreen mode Exit fullscreen mode
  • jest types is a inteliscense to use jest:
  yarn add @types/jest -D
Enter fullscreen mode Exit fullscreen mode
  • Supertest is a framework to simulate http requisitions:
  yarn add supertest -D
Enter fullscreen mode Exit fullscreen mode

Now we need to make initial jest config.

To do that we execute the command below:

  yarn jest --init
Enter fullscreen mode Exit fullscreen mode

After that the console make some questions to you, you need to answer like the image below:

Alt Text

Now you will find a file called "jest.config.js" on your root project.

The next step is ajust this config file like below:

  • Bail is the option we set to define the number of errors that make the tests break, in this case i always like to set one:
 bail: 1,
Enter fullscreen mode Exit fullscreen mode
  • Clearmocks is the option that clear mocks after tests, this option we set true:
clearMocks: true,
Enter fullscreen mode Exit fullscreen mode
  • collectCoverage this option enable or disable the coe coverage, i like to set as true:
collectCoverage: true,
Enter fullscreen mode Exit fullscreen mode
  • collectCoverageFrom this option define the path or file s to collect the coverage, usually i set the path where stay my business logic:
collectCoverageFrom: [
    'src/app/Controllers/*.js',
  ],
Enter fullscreen mode Exit fullscreen mode
  • coverageDirectory is the place where jest can put the coverage result, i usualy put coverage inside the test folder:
 coverageDirectory: '__tests__/coverage',
Enter fullscreen mode Exit fullscreen mode
  • coverageReporters this option set the type of reporters for coverage result, i like to user reports below:
 coverageReporters: ['text', 'lcov', 'json'],
Enter fullscreen mode Exit fullscreen mode
  • testMatch this option set the test files extensions:
  testMatch: ['**/__tests__/**/*.test.js'],

Enter fullscreen mode Exit fullscreen mode

Now we can create the folder structure as the image below:

Alt Text

And that is it, now you reandy to starting test your api with jest!

Alt Text

Top comments (0)

🌚 Life is too short to browse without dark mode