I tried to writing test cases with fastify using Tap npm package. But I have some question about my implementation.Here is the my test case file code.
server.test.js will look like
const tap = require('tap')
const mongoose = require('mongoose')
const buildServer = require('../server')
tap.test('requests the `/health-check` route', async function (t) {
const fastify = buildServer()
t.teardown(() => {
fastify.close()
})
const response = await fastify.inject({
method: 'GET',
url: 'health-check'
})
t.equal(200, response.statusCode)
})
When I write test cases for different modules available in my app I will create new test files according to the module. Let's say module A. here is the code for module A test case.
const { test } = require('tap')
const { faker } = require('@faker-js/faker')
const buildServer = require('../../../server')
const mongoose = require('mongoose')
const { redisClient } = require('../../../plugins/redis')
test('It will test artist module', async (t) => {
const fastify = buildServer()
t.teardown(() => {
fastify.close()
redisClient.quit()
mongoose.connection.close()
})
t.test('It should return data by Id', async () => {
const response = await fastify.inject({
method: 'GET',
url: '/api/v1/artist/',
query: {
id: "1"
}
})
const payload = response.json()
console.log('payload', payload)
t.equal(200, response.statusCode)
})
})
My concern is I need to buildServer server in every test case file and It will eventually create db connection.So is this good way to buildServer in every test file? And how to avoid duplicate imports between those test files? and one more issue I facing is I need to manually close db connection in every test case.
It it the correct way that I am trying to implement test cases ? if not then please provide some example with tap using fastify