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

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

    1. fastify
    2. .inject({
    3. method: String,
    4. url: String,
    5. query: Object,
    6. payload: Object,
    7. headers: Object
    8. })
    9. .then(response => {
    10. // your tests
    11. })
    12. .catch(err => {
    13. // handle error
    14. })

    Async await is supported as well!

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

    Example:

    app.js

    test.js

    1. const tap = require('tap')
    2. tap.test('GET `/` route', t => {
    3. t.plan(4)
    4. // At the end of your tests it is highly recommended to call `.close()`
    5. // to ensure that all connections to external services get closed.
    6. t.tearDown(() => fastify.close())
    7. fastify.inject({
    8. method: 'GET',
    9. url: '/'
    10. }, (err, response) => {
    11. t.error(err)
    12. t.strictEqual(response.statusCode, 200)
    13. t.strictEqual(response.headers['content-type'], 'application/json; charset=utf-8')
    14. t.deepEqual(JSON.parse(response.payload), { hello: 'world' })
    15. })
    16. })

    Example:

    Uses app.js from the previous example.

    test-listen.js (testing with )

    1. const tap = require('tap')
    2. const request = require('request')
    3. const buildFastify = require('./app')
    4. tap.test('GET `/` route', t => {
    5. t.plan(5)
    6. const fastify = buildFastify()
    7. fastify.listen(0, (err) => {
    8. t.error(err)
    9. request({
    10. method: 'GET',
    11. url: 'http://localhost:' + fastify.server.address().port
    12. }, (err, response, body) => {
    13. t.error(err)
    14. t.strictEqual(response.statusCode, 200)
    15. t.strictEqual(response.headers['content-type'], 'application/json; charset=utf-8')
    16. t.deepEqual(JSON.parse(body), { hello: 'world' })
    17. })
    18. })
    19. })

    test-ready.js (testing with SuperTest)

    • Isolate your test by passing the {only: true} option
    1. test('should ...', {only: true}, t => ...)
    • Run tap using npx
    1. > npx tap -O -T --node-arg=--inspect-brk test/<test-file.test.js>
    • -O specifies to run tests with the only option enabled
    • -T specifies not to timeout (while you're debugging)
    • —node-arg=—inspect-brk will launch the node debugger
    • In VS Code, create and launch a Node.js: Attach debug configuration. No modification should be necessary.Now you should be able to step through your test file (and the rest of fastify) in your code editor.