Boost your code coverage with API Tests
Tags: testing, javascript, codequality, pactumjs
Published: 2021-05-07 17:40:26

Code coverage is an important quality metric that determines the number of lines of source code that is tested & covered by automated tests. Usually, developers achieve code coverage close to **80%** by writing **unit tests** (*most popular tests to generate code coverage*).

#### Targeted Code

In general unit tests targets happy paths, core business logic, and rarely sad paths. Most likely they can give us close to **80%** of code coverage. The remaining **20%** of source code might be responsible for handling external interfaces and exceptions/errors. Unit tests generally omit testing external interface logic that interacts with outside applications & databases.

Testing the external interface logic at the early phases of SDLC is very critical for delivering a quality software product.

#### API Testing

API testing is critical for automating testing because APIs now serve as the primary interface to application logic. API tests could greatly improve the code coverage of applications and the overall confidence in the product.

Let's see how to get code coverage from API tests.

## Example

In this example, we will be looking at a basic **Node.js** web application.

### Source Code

Look at the sample web app server written in [express](https://expressjs.com/). (*Express is a minimal and flexible Node.js web application framework*)

```js
// index.js
const express = require('express');
const app = express();
const port = 3333;

app.get('/hello', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`App listening at http://localhost:${port}`);
});
```

To run the application, execute the below command in terminal

```sh
node index.js
```

### API Tests

Look at the sample API tests written using [PactumJS](https://pactumjs.github.io/) and [mocha](https://mochajs.org/).

{% github pactumjs/pactum no-readme %}

```js
// app.test.js
const pactum = require('pactum');

describe('App', () => {

  it('GET /hello', async () => {
    await pactum.spec()
      .get('http://localhost:3333/hello')
      .expectStatus(200)
      .expectBody('Hello World!');
  });

});
```

To run the tests, execute the below command in terminal

```sh
mocha app.test.js
```

### Code Coverage

We have seen how to run the application & execute tests against it. To generate code coverage from API tests, we will be using an npm package called [nyc](https://www.npmjs.com/package/nyc).

Install the package globally

```sh
npm i nyc -g
```

Now run your application with this magical tool **nyc**.

```sh
nyc node index.js
```

###### Output

![output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8zqyqviizmp2kwom40yx.png)

Run Tests

```sh
mocha app.test.js
```

###### Output

![output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xp63k4ab8qbqgl61l0rg.png)

Stop the application by pressing `CTRL + c`. Now the **nyc** tool will generate and display the code coverage in the terminal.

###### Output

![output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2npwkizvxnqe0r3y8pj7.png)

> For real and complex web applications, the code-coverage setup might not be straightforward. It might require additional steps and advanced configurations.

## Conclusion

Importance of API testing is growing day by day. Not only using these tests for validating applications but also for generating code coverage metrics is an added advantage. 

In most scenarios, a simple API test could cover a big chunk of source code. It means with fewer API Tests we can get more code coverage and confidence in the application.