如何在Fastify中使用Jest和Supertest?

huangapple go评论67阅读模式
英文:

How to use Jest and Supertest with Fastify?

问题

我正在尝试在Fastify中使用Jest和Supertest。我有这个测试文件。

// @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('应该返回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

但我总是超时... 有人能提供如何在Fastify中使用Jest和Supertest的示例吗?

英文:

I'm trying to use Jest and Supertest with Fastify. I have this test file.

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

My 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

But I always get a timeout... Could anyone provide an example of how to use Jest and Supertest with Fastify?

答案1

得分: 1

以下是翻译好的内容:

在官方文档底部有一个关于使用 supertest 编写测试的示例。请查看 testing

确保调用 fastify.register() API 的 done 回调函数。

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打开,在Microsoft Edge上运行 npm run test 时可能会出现错误)。

英文:

There is an example in the official document at the bottom about writing testings with supertest. See testing

Make sure you call the done callback of the fasity.register() API.

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

Test result:

❯ 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(Open using Chrome, there is a bug when run npm run test using Microsoft Edge)

huangapple
  • 本文由 发表于 2023年1月5日 04:44:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75011078.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定