跳至主要內容
版本:最新版 (v5.0.x)

測試

測試是開發應用程式最重要的環節之一。Fastify 在測試方面非常彈性,並且與大多數測試框架相容(例如 Tap,以下範例中使用此框架)。

應用程式

我們來 cd 到一個名為「testing-example」的新目錄,並在終端機中輸入 npm init -y

執行 npm i fastify && npm i tap pino-pretty -D

分離關注點讓測試變得容易

首先,我們將應用程式碼與伺服器程式碼分開

app.js:

'use strict'

const fastify = require('fastify')

function build(opts={}) {
const app = fastify(opts)
app.get('/', async function (request, reply) {
return { hello: 'world' }
})

return app
}

module.exports = build

server.js:

'use strict'

const server = require('./app')({
logger: {
level: 'info',
transport: {
target: 'pino-pretty'
}
}
})

server.listen({ port: 3000 }, (err, address) => {
if (err) {
server.log.error(err)
process.exit(1)
}
})

使用 fastify.inject() 的好處

多虧了 light-my-request,Fastify 內建了對虛擬 HTTP 注入的支援。

在引入任何測試之前,我們將使用 .inject 方法對我們的路由發出虛擬請求

app.test.js:

'use strict'

const build = require('./app')

const test = async () => {
const app = build()

const response = await app.inject({
method: 'GET',
url: '/'
})

console.log('status code: ', response.statusCode)
console.log('body: ', response.body)
}
test()

首先,我們的程式碼將在非同步函式內執行,以便我們可以使用 async/await。

.inject 確保所有註冊的外掛程式都已啟動,並且我們的應用程式已準備好進行測試。最後,我們傳遞要使用請求方法和路由。使用 await 我們可以在沒有回呼的情況下儲存回應。

在您的終端機中執行測試檔案 node app.test.js

status code:  200
body: {"hello":"world"}

使用 HTTP 注入進行測試

現在我們可以用實際的測試取代 console.log 呼叫!

在您的 package.json 中將 "test" 指令碼變更為

"test": "tap --reporter=list --watch"

app.test.js:

'use strict'

const { test } = require('tap')
const build = require('./app')

test('requests the "/" route', async t => {
const app = build()

const response = await app.inject({
method: 'GET',
url: '/'
})
t.equal(response.statusCode, 200, 'returns a status code of 200')
})

最後,在終端機中執行 npm test 並查看您的測試結果!

inject 方法可以做的遠比簡單的對 URL 發出 GET 請求還要多

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

.inject 方法也可以透過省略回呼函式來鏈接

fastify
.inject()
.get('/')
.headers({ foo: 'bar' })
.query({ foo: 'bar' })
.end((err, res) => { // the .end call will trigger the request
console.log(res.payload)
})

或者在 Promise 版本中

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

也支援 Async await!

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

另一個範例:

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.equal(response.statusCode, 200)
t.equal(response.headers['content-type'], 'application/json; charset=utf-8')
t.same(response.json(), { hello: 'world' })
})
})

使用執行中的伺服器進行測試

在伺服器使用 fastify.listen() 啟動後,或在使用 fastify.ready() 初始化路由和外掛程式後,也可以對 Fastify 進行測試。

範例:

使用先前範例的 app.js

test-listen.js(使用 undici 進行測試)

const tap = require('tap')
const { Client } = require('undici')
const buildFastify = require('./app')

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

const fastify = buildFastify()

await fastify.listen()

const client = new Client(
'https://127.0.0.1:' + fastify.server.address().port, {
keepAliveTimeout: 10,
keepAliveMaxTimeout: 10
}
)

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)
})

或者,從 Node.js 18 開始,可以使用 fetch,而無需任何額外的依賴項

test-listen.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(
'https://127.0.0.1:' + 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' })
})

test-ready.js(使用 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.same(response.body, { hello: 'world' })
})

如何檢視 tap 測試

  1. 透過傳遞 {only: true} 選項來隔離您的測試
test('should ...', {only: true}, t => ...)
  1. 使用 npx 執行 tap
> npx tap -O -T --node-arg=--inspect-brk test/<test-file.test.js>
  • -O 指定執行時啟用 only 選項的測試
  • -T 指定不要逾時(當您正在偵錯時)
  • --node-arg=--inspect-brk 將啟動節點偵錯工具
  1. 在 VS Code 中,建立並啟動一個 Node.js: Attach 偵錯設定。無需進行修改。

現在您應該可以在您的程式碼編輯器中逐步執行您的測試檔案(以及 Fastify 的其餘部分)。

外掛程式

我們來 cd 到一個名為「testing-plugin-example」的新目錄,並在終端機中輸入 npm init -y

執行 npm i fastify fastify-plugin && npm i tap -D

plugin/myFirstPlugin.js:

const fP = require("fastify-plugin")

async function myPlugin(fastify, options) {
fastify.decorateRequest("helloRequest", "Hello World")
fastify.decorate("helloInstance", "Hello Fastify Instance")
}

module.exports = fP(myPlugin)

外掛程式的基本範例。請參閱外掛程式指南

test/myFirstPlugin.test.js:

const Fastify = require("fastify");
const tap = require("tap");
const myPlugin = require("../plugin/myFirstPlugin");

tap.test("Test the Plugin Route", async t => {
// Create a mock fastify application to test the plugin
const fastify = Fastify()

fastify.register(myPlugin)

// Add an endpoint of your choice
fastify.get("/", async (request, reply) => {
return ({ message: request.helloRequest })
})

// Use fastify.inject to fake a HTTP Request
const fastifyResponse = await fastify.inject({
method: "GET",
url: "/"
})

console.log('status code: ', fastifyResponse.statusCode)
console.log('body: ', fastifyResponse.body)
})

深入瞭解 fastify.inject()。在您的終端機中執行測試檔案 node test/myFirstPlugin.test.js

status code:  200
body: {"message":"Hello World"}

現在我們可以用實際的測試取代 console.log 呼叫!

在您的 package.json 中將 "test" 指令碼變更為

"test": "tap --reporter=list --watch"

為端點建立 tap 測試。

test/myFirstPlugin.test.js:

const Fastify = require("fastify");
const tap = require("tap");
const myPlugin = require("../plugin/myFirstPlugin");

tap.test("Test the Plugin Route", async t => {
// Specifies the number of test
t.plan(2)

const fastify = Fastify()

fastify.register(myPlugin)

fastify.get("/", async (request, reply) => {
return ({ message: request.helloRequest })
})

const fastifyResponse = await fastify.inject({
method: "GET",
url: "/"
})

t.equal(fastifyResponse.statusCode, 200)
t.same(JSON.parse(fastifyResponse.body), { message: "Hello World" })
})

最後,在終端機中執行 npm test 並查看您的測試結果!

測試 .decorate().decorateRequest()

test/myFirstPlugin.test.js:

const Fastify = require("fastify");
const tap = require("tap");
const myPlugin = require("../plugin/myFirstPlugin");

tap.test("Test the Plugin Route", async t => {
t.plan(5)
const fastify = Fastify()

fastify.register(myPlugin)

fastify.get("/", async (request, reply) => {
// Testing the fastify decorators
t.not(request.helloRequest, null)
t.ok(request.helloRequest, "Hello World")
t.ok(fastify.helloInstance, "Hello Fastify Instance")
return ({ message: request.helloRequest })
})

const fastifyResponse = await fastify.inject({
method: "GET",
url: "/"
})
t.equal(fastifyResponse.statusCode, 200)
t.same(JSON.parse(fastifyResponse.body), { message: "Hello World" })
})