API Testing with Clerk and Express
Tags: webdev, javascript, clerk, express
Published: 2024-03-25 18:47:22

## Introduction
This guide outlines the process of setting up API testing with an Express server using Clerk middlewares for route protection and Jest with Supertest as the testing framework. Before proceeding, ensure you have an Express server configured, Clerk middlewares implemented for route protection, and have selected a testing framework. The procedure involves generating a long-lived JWT token using Clerk, fetching the token, and setting up API testing by adding authentication headers to requests sent to protected endpoints.

## Prerequisites - 
- you have a express server setup
- you are using [Clerk middlewares](https://clerk.com/docs/backend-requests/handling/nodejs) to protect routes
- you have selected a testing framework. In my case, it's [Jest](https://jestjs.io/) with [Supertest](https://github.com/ladjs/supertest#readme)

## The procedure
### Step 1 - Generate long-lived JWT
[Same as mentioned here](https://clerk.com/docs/testing/postman-or-insomnia#generate-long-lived-jwt-template)
- Go to the [JWT Templates page](https://dashboard.clerk.com/last-active?path=jwt-templates)

![Clerk JWT templates page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v1r7uga7x1sxgvrhp8bg.png)

- Create a new template
- Select blank on the dialog
- Name it something like `testing-template`
- Set the token lifetime to the maximum value - `315360000` (10 years)
- If you added custom claims to the normal session token, then you should add the same claims to your JWT Template

### Step 2 - Fetch long-lived token
- Go to the [Clerk Dashboard](https://dashboard.clerk.com/)
- Create a new user with an email like `test.user@test.com` and any password
- Click on the impersonate user button after the user is created.
![Clerk Impersonate user button](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fyzn1i2sgd5muy9ixbs0.png)
- This will redirect you to a new page
- Open the dev console on that page by pressing `Ctrl+Shift+I`
- Paste or type this in - 
  ```js
  await window.Clerk.session.getToken({ template: "testing-template" });
  ```
make sure to replace `testing-template` with the name you chose while creating the jwt template in Step 1
- The output will be a jwt token
- copy this token

### Step 3 - Setup API Testing
- add a new entry in your `.env` file of your express server 
```bash
TEST_USER_TOKEN="<your-jwt-token-here>"
```
- add auth headers to your request to a protected endpoint
```ts
import request from "supertest";
import app from "../../app";

const userToken = process.env.TEST_USER_TOKEN;
if (!userToken) {
  throw new Error(
    "Provide a TEST_USER_TOKEN env variable for testing - visit: https://dev.to/mad/api-testing-with-clerk-and-express-2i56"
  );
}

describe("POST /api/product", () => {
  it("responds with a new todo", async () =>
    request(app)
      .post("/api/product")
      .set("Accept", "application/json")
      // FOCUS ON THIS
      .auth(userToken, { type: "bearer" })
      .send({
        title: "test product 1",
        description: "test description",
        price: 2.0,
      })
      .expect("Content-Type", /json/)
      .expect(200)
      .then((res) => {
        expect(res.body).toHaveProperty("id");
        id = res.body.id;
      }));
});
```
- run your tests!