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 to protect routes
- you have selected a testing framework. In my case, it's Jest with Supertest
The procedure
Step 1 - Generate long-lived JWT
- Go to the JWT Templates page
- 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
- 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.
- 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!
Top comments (1)
Thanks a lot, I spent hours trying to figure out how to get JWT that does not expire after 60 seconds