Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: add test examples with undici and fetch #4300

Merged
merged 1 commit into from Oct 6, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
67 changes: 50 additions & 17 deletions docs/Guides/Testing.md
Expand Up @@ -243,33 +243,66 @@ after initializing routes and plugins with `fastify.ready()`.

Uses **app.js** from the previous example.

**test-listen.js** (testing with
[`Request`](https://www.npmjs.com/package/request))
**test-listen.js** (testing with [`undici`](https://www.npmjs.com/package/undici))
```js
const tap = require('tap')
const request = require('request')
const { Client } = require('undici')
const buildFastify = require('./app')

tap.test('GET `/` route', t => {
t.plan(5)
tap.test('should work with undici', async t => {
t.plan(2)

const fastify = buildFastify()

t.teardown(() => fastify.close())
await fastify.listen()

fastify.listen({ port: 0 }, (err) => {
t.error(err)
const client = new Client(
'http://localhost:' + fastify.server.address().port, {
keepAliveTimeout: 10,
keepAliveMaxTimeout: 10
This conversation was marked as resolved.
Show resolved Hide resolved
}
)
This conversation was marked as resolved.
Show resolved Hide resolved

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

const response = await client.request({ method: 'GET', path: '/' })

t.equal(await response.body.text(), '{"hello":"world"}')
t.equal(response.statusCode, 200)
})
```

Alternatively, starting with Node.js 18,
[`fetch`](https://nodejs.org/docs/latest-v18.x/api/globals.html#fetch)
may be used without requiring any extra dependencies:

**test-listen.js**
```js
const tap = require('tap')
const buildFastify = require('./app')

tap.test('should work with fetch', async t => {
t.plan(3)

const fastify = buildFastify()

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

await fastify.listen()

const response = await fetch(
'http://localhost:' + fastify.server.address().port
)

t.equal(response.status, 200)
t.equal(
response.headers.get('content-type'),
'application/json; charset=utf-8'
)
t.has(await response.json(), { hello: 'world' })
})
```

Expand Down