Я пытаюсь использовать Jest и Supertest с Fastify. У меня есть этот тестовый файл.
// @ts-nocheck
import { FastifyInstance } from 'fastify'
import request from 'supertest'
import app from '../app'
let server: FastifyInstance
beforeAll(async () => {
server = app.server;
})
afterAll(() => {
server.close()
})
test('Should get a 200 OK', async () => {
const response = await request(server).get('/')
expect(response.status).toBe(200)
})
Мой app.ts
:
import fastify from 'fastify'
import dotenv from 'dotenv'
dotenv.config()
import appRoute from './routes/app'
const app = fastify({ logger: true })
app.register(appRoute)
export default app
Но я всегда получаю тайм-аут... Может ли кто-нибудь привести пример использования Jest и Supertest с Fastify?
В официальном документе внизу есть пример написания тестов с помощью supertest
. Смотрите тестирование
Убедитесь, что вы вызываете обратный вызов done
API fasity.register()
.
index.js
:
const Fastify = require('fastify');
const app = Fastify({ logger: true });
app.register((instance, opts, done) => {
instance.get('/', (request, reply) => {
reply.send({ hello: 'world' });
});
done();
});
module.exports = app;
index.test.js
:
const supertest = require('supertest');
const app = require('./');
afterAll(() => app.close());
test('GET `/` route', async () => {
await app.ready();
const response = await supertest(app.server)
.get('/')
.expect(200)
.expect('Content-Type', 'application/json; charset=utf-8');
expect(response.body).toEqual({ hello: 'world' });
});
Результат испытаний:
❯ npm run test
$ jest
{"level":30,"time":1673234788774,"pid":70,"hostname":"noderfv2fs-ky0o","reqId":"req-1","req":{"method":"GET","url":"/","hostname":"127.0.0.1:62766"},"msg":"incoming request"}
{"level":30,"time":1673234788777,"pid":70,"hostname":"noderfv2fs-ky0o","reqId":"req-1","res":{"statusCode":200},"responseTime":2.5850000000000364,"msg":"request completed"}
PASS ./index.test.js
✓ GET `/` route (489 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 2.269 s, estimated 3 s
Ran all test suites.
stackblitz(Открыть с помощью Chrome, при запуске npm run test
с помощью Microsoft Edge возникает ошибка)
Почему вы не используете app.inject?