Fastify comes with built-in support for fake http injection thanks to .
To inject a fake http request, use the inject
method:
fastify
.inject({
method: String,
url: String,
query: Object,
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
test.js
const tap = require('tap')
tap.test('GET `/` route', t => {
t.plan(4)
// 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' })
})
})
Example:
Uses app.js from the previous example.
test-listen.js (testing with )
const tap = require('tap')
const request = require('request')
const buildFastify = require('./app')
tap.test('GET `/` route', t => {
t.plan(5)
const fastify = buildFastify()
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
)
- Isolate your test by passing the
{only: true}
option
test('should ...', {only: true}, t => ...)
- Run
tap
usingnpx
> npx tap -O -T --node-arg=--inspect-brk test/<test-file.test.js>
-O
specifies to run tests with theonly
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 offastify
) in your code editor.