In modern software development, ensuring the reliability of APIs is crucial. Fastify, a fast and low-overhead web framework for Node.js, is widely used for building APIs. Automating the testing process of Fastify APIs can significantly improve development efficiency and code quality. This article explores how to automate Fastify API testing using GitHub Actions and command line tools.

Setting Up Fastify API Tests

Before automating, ensure you have a Fastify project with tests written using a testing framework such as Jest or Mocha. Your tests should be executable via command line, typically with a script in your package.json file.

Example test script in package.json:

{
  "scripts": {
    "test": "jest"
  }
}

Creating a GitHub Actions Workflow

GitHub Actions allows you to automate workflows triggered by events such as push or pull requests. To run your Fastify tests automatically, create a workflow file in your repository.

In your repository, add a new file at .github/workflows/test.yml with the following content:

name: Fastify API Tests

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v3

      - name: Set up Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '16'

      - name: Install dependencies
        run: npm install

      - name: Run tests
        run: npm test

Using Command Line Tools for Additional Automation

For more advanced automation, incorporate command line tools like cURL or HTTPie to perform API requests directly from scripts. These tools can be integrated into your testing scripts or CI workflows to verify API responses.

Example using cURL in a script:

curl -s -o /dev/null -w "%{http_code}" http://localhost:3000/endpoint | grep 200

This command checks if the API endpoint returns a 200 OK status code. You can extend this approach to validate response bodies and headers as needed.

Automating Tests in CI/CD Pipelines

Integrate your command line tests into your CI/CD pipeline for continuous verification. For example, in a Dockerized environment, you can run tests inside a container during build time.

Example Docker command:

docker run --rm -v $(pwd):/app -w /app node:16 bash -c "npm install && npm test"

Conclusion

Automating Fastify API testing with GitHub Actions and command line tools streamlines your development process, reduces manual effort, and enhances code reliability. By setting up automated workflows, you ensure that your APIs are continuously tested and maintained at a high standard.