Testing | Fastify (2024)

Testing

Testing is one of the most important parts of developing an application. Fastify is very flexible when it comes to testing and is compatible with most testing frameworks (such as Tap, which is used in the examples below).

Testing with http injection

Fastify comes with built-in support for fake http injection thanks to light-my-request.

To inject a fake http request, use the inject method:

fastify.inject({
method: String,
url: String,
payload: Object,
headers: Object
}, (error, response) => {
// your tests
})

or in the promisified version

fastify
.inject({
method: String,
url: String,
payload: Object,
headers: Object
})
.then(response => {
// your tests
})
.catch(err => {
// handle error
})

Async await is supported as well!

try {
const res = await fastify.inject({ method: String, url: String, payload: Object, headers: Object })
// your tests
} catch (err) {
// handle error
}

Example:

app.js

const Fastify = require('fastify')

function buildFastify () {
const fastify = Fastify()

fastify.get('/', function (request, reply) {
reply.send({ hello: 'world' })
})

return fastify
}

module.exports = buildFastify

test.js

const tap = require('tap')
const buildFastify = require('./app')

tap.test('GET `/` route', t => {
t.plan(4)

const fastify = buildFastify()

// At the end of your tests it is highly recommended to call `.close()`
// to ensure that all connections to external services get closed.
t.tearDown(() => fastify.close())

fastify.inject({
method: 'GET',
url: '/'
}, (err, response) => {
t.error(err)
t.strictEqual(response.statusCode, 200)
t.strictEqual(response.headers['content-type'], 'application/json; charset=utf-8')
t.deepEqual(JSON.parse(response.payload), { hello: 'world' })
})
})

Testing with a running server

Fastify can also be tested after starting the server with fastify.listen() or after initializing routes and plugins with fastify.ready().

Example:

Uses app.js from the previous example.

test-listen.js (testing with Request)

const tap = require('tap')
const request = require('request')
const buildFastify = require('./app')

tap.test('GET `/` route', t => {
t.plan(5)

const fastify = buildFastify()

t.tearDown(() => fastify.close())

fastify.listen(0, (err) => {
t.error(err)

request({
method: 'GET',
url: 'http://localhost:' + fastify.server.address().port
}, (err, response, body) => {
t.error(err)
t.strictEqual(response.statusCode, 200)
t.strictEqual(response.headers['content-type'], 'application/json; charset=utf-8')
t.deepEqual(JSON.parse(body), { hello: 'world' })
})
})
})

test-ready.js (testing with SuperTest)

const tap = require('tap')
const supertest = require('supertest')
const buildFastify = require('./app')

tap.test('GET `/` route', async (t) => {
const fastify = buildFastify()

t.tearDown(() => fastify.close())

await fastify.ready()

const response = await supertest(fastify.server)
.get('/')
.expect(200)
.expect('Content-Type', 'application/json; charset=utf-8')
t.deepEqual(response.body, { hello: 'world' })
})

Testing | Fastify (2024)
Top Articles
Reports of Bitcoin’s Demise Are Greatly Exaggerated. Here’s Why...
Want to work in crypto? University programs can give job seekers a leg up
Bubble Guppies Who's Gonna Play The Big Bad Wolf Dailymotion
Victor Spizzirri Linkedin
Radikale Landküche am Landgut Schönwalde
Uihc Family Medicine
craigslist: kenosha-racine jobs, apartments, for sale, services, community, and events
Online Reading Resources for Students & Teachers | Raz-Kids
Ohiohealth Esource Employee Login
Milk And Mocha GIFs | GIFDB.com
Mawal Gameroom Download
New Mexico Craigslist Cars And Trucks - By Owner
Oxford House Peoria Il
The Binding of Isaac
C Spire Express Pay
Think Up Elar Level 5 Answer Key Pdf
[Birthday Column] Celebrating Sarada's Birthday on 3/31! Looking Back on the Successor to the Uchiha Legacy Who Dreams of Becoming Hokage! | NARUTO OFFICIAL SITE (NARUTO & BORUTO)
Haunted Mansion Showtimes Near Millstone 14
Gayla Glenn Harris County Texas Update
Yonkers Results For Tonight
Ceramic tiles vs vitrified tiles: Which one should you choose? - Building And Interiors
Cona Physical Therapy
2004 Honda Odyssey Firing Order
Ultra Ball Pixelmon
Big Boobs Indian Photos
Obituaries, 2001 | El Paso County, TXGenWeb
Donald Trump Assassination Gold Coin JD Vance USA Flag President FIGHT CIA FBI • $11.73
Otis Offender Michigan
Workboy Kennel
Worlds Hardest Game Tyrone
Minecraft Jar Google Drive
Domino's Delivery Pizza
Chs.mywork
Grapes And Hops Festival Jamestown Ny
Domina Scarlett Ct
KM to M (Kilometer to Meter) Converter, 1 km is 1000 m
3302577704
Temu Y2K
159R Bus Schedule Pdf
303-615-0055
Ethan Cutkosky co*ck
Exploring the Digital Marketplace: A Guide to Craigslist Miami
'The Night Agent' Star Luciane Buchanan's Dating Life Is a Mystery
Scythe Banned Combos
Spreading Unverified Info Crossword Clue
Bridgeport Police Blotter Today
Value Village Silver Spring Photos
Phunextra
Call2Recycle Sites At The Home Depot
Mike De Beer Twitter
Latest Posts
Article information

Author: Gov. Deandrea McKenzie

Last Updated:

Views: 6382

Rating: 4.6 / 5 (46 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Gov. Deandrea McKenzie

Birthday: 2001-01-17

Address: Suite 769 2454 Marsha Coves, Debbieton, MS 95002

Phone: +813077629322

Job: Real-Estate Executive

Hobby: Archery, Metal detecting, Kitesurfing, Genealogy, Kitesurfing, Calligraphy, Roller skating

Introduction: My name is Gov. Deandrea McKenzie, I am a spotless, clean, glamorous, sparkling, adventurous, nice, brainy person who loves writing and wants to share my knowledge and understanding with you.