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
The 18 highest paying engineering jobs - Degreechoices.com
Smart Contract Security Researcher Salary in 2024 (Updated Daily) | Crypto Jobs List
Koopa Wrapper 1 Point 0
Craigslist Monterrey Ca
Avonlea Havanese
Phcs Medishare Provider Portal
Dollywood's Smoky Mountain Christmas - Pigeon Forge, TN
Chris wragge hi-res stock photography and images - Alamy
Santa Clara College Confidential
Best Theia Builds (Talent | Skill Order | Pairing + Pets) In Call of Dragons - AllClash
Bernie Platt, former Cherry Hill mayor and funeral home magnate, has died at 90
Valentina Gonzalez Leaked Videos And Images - EroThots
Nexus Crossword Puzzle Solver
Little Rock Arkansas Craigslist
Builders Best Do It Center
Mephisto Summoners War
Inevitable Claymore Wow
ᐅ Bosch Aero Twin A 863 S Scheibenwischer
Procore Championship 2024 - PGA TOUR Golf Leaderboard | ESPN
Leader Times Obituaries Liberal Ks
Straight Talk Phones With 7 Inch Screen
Msu 247 Football
Nhl Tankathon Mock Draft
Traveling Merchants Tack Diablo 4
Lista trofeów | Jedi Upadły Zakon / Fallen Order - Star Wars Jedi Fallen Order - poradnik do gry | GRYOnline.pl
Dr Ayad Alsaadi
Scream Queens Parents Guide
Walmart Pharmacy Near Me Open
At 25 Years, Understanding The Longevity Of Craigslist
Mdt Bus Tracker 27
Harbor Freight Tax Exempt Portal
New Stores Coming To Canton Ohio 2022
Restored Republic
Alternatieven - Acteamo - WebCatalog
Metro By T Mobile Sign In
Kltv Com Big Red Box
Craigslist Gigs Norfolk
Forager How-to Get Archaeology Items - Dino Egg, Anchor, Fossil, Frozen Relic, Frozen Squid, Kapala, Lava Eel, and More!
Metra Schedule Ravinia To Chicago
7543460065
10 games with New Game Plus modes so good you simply have to play them twice
Flappy Bird Cool Math Games
Funkin' on the Heights
The Cutest Photos of Enrique Iglesias and Anna Kournikova with Their Three Kids
Aloha Kitchen Florence Menu
Motorcycles for Sale on Craigslist: The Ultimate Guide - First Republic Craigslist
Zits Comic Arcamax
Urban Airship Acquires Accengage, Extending Its Worldwide Leadership With Unmatched Presence Across Europe
Vcuapi
Booked On The Bayou Houma 2023
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.