Testing an Express.js API with Vitest
Learn how to create super fast tests with Vitest and Supertest for your Express.js API.
April 11, 2024
π» Vitest π» Express.js π» Supertest
Step 1: Express set up
Init the repository
Create a new directory for your project and navigate into it:
Then, initialize a new Node.js project:
Next, install the dependencies:
Create API files
Create a new file and add our routes so you can export them and start the server with those routes and also be able to test them:
Add:
Create the file that will initialize the server, we can run it with the βnode app.jsβ command:
Update package.json to be able to use ECMAScript modules. Your file should look like this:
Now you can test your API using the following command!
Step 2: Vitest set up
Create Test files
Create the file that will be read by vitest and write the test:
Add:
Step 3: Test your API!
To run the test execute:
You got it!
You can make this process easier by modifying the package.json scripts like this: