Fastify server testing
Fastify tutorial in 4 parts
- Part 1: starting the server ✅
- Part 2: first route ✅
- Part 3: render view with Amedia Component ✅
- Part 4: server testing 👈 You are here
Remember how we've exported buildApp
from app.js
. Well now we'll see exactly why. You see, there are different testing strategies. You have your end-to-end testing, regression testing, but what we'll focus on today is integration testing. More specifically, we want to test that /example
route returns a html string.
In order to do that, we can take advantage of native node test runner. There are other libraries for testing out there, but for this tutorial, we shall focus on native node test runner.
Create a folder called tests
. Inside create a folder named server
and create a file called server.test.js
inside server
folder.
We'll start by importing our dependencies:
import assert from 'node:assert';
import { afterEach, beforeEach, describe, it } from 'node:test';
Then we can start our testing:
import assert from 'node:assert';
import { afterEach, beforeEach, describe, it } from 'node:test';
const basePath = 'http://localhost:3000';
describe('buildApp', async () => {
let app;
beforeEach(async () => {
const { buildApp } = await import('../../app.js');
app = await buildApp();
});
afterEach(async () => {
await app.close();
});
describe('GET /example/embed', () => {
it('will return 200', async () => {
const res = await app.inject({
url: `${basePath}/example/embed`,
});
assert.deepStrictEqual(res.statusCode, 200);
});
});
});
In package.json, add test
run command, and copy the following code: node --test --experimental-test-coverage --import tsx ./tests/**/*.test.ts
Now run npm run test
. It should return one green test.
Now let's take a closer look at this code. In beforeEach
function we are asigning a new instance of our server. Here await buildApp();
we can creating an instance of our server, so that all the modules inside of our server are included. That will make testing much easier, and that's why we needed to export createApp
.
The reason why we have it in beforeEach
block is to create a new instance for each test.
As you can see from afterEach
method, we then close our server after each test.
Next in app.inject
, we actually inject url in our server, telling it where to go.
And lastly, we are useing deepStrictEqual
in order to assert that the status code is 200
.
This is a very simple test, but the moral of this story remains the same. In order to consume our app safely, we need to know that it's running as we intended.
Congrats 🥳 now we have voth seasoned and consumed our application. But this was just an appetizer.
For the main course, we'll have a deeper dive into more complex subjects. Like how to setup routes with ZOD, how to generate swagger documentation. How to create views with Svelte and a more indepth look at testing.
For now thank you for reading this tutorial 🥳