【问题标题】:How can I test my express rest api built with MikroORM?如何测试使用 MikroORM 构建的 express rest api?
【发布时间】:2021-10-23 10:00:07
【问题描述】:

index.ts:

import 'reflect-metadata'
import express from 'express'
import { EntityManager, EntityRepository, MikroORM, RequestContext } from '@mikro-orm/core'
import options from '../mikro-orm.config'
import { Music } from './entities/music.entity'
import router from './routes'

const app = express()

export const DI = {} as {
    orm: MikroORM,
    em: EntityManager,
    musicRepository: EntityRepository<Music>
}

async function bootstrap() {

    DI.orm = await MikroORM.init(options)

    DI.em = DI.orm.em
    DI.musicRepository = DI.orm.em.getRepository(Music)

    app.use(express.json())
    app.use(express.urlencoded({ extended: true }))
    app.use((req, res, next) => RequestContext.create(DI.orm.em, next))
    app.use(router)

    return { app, DI }

}

bootstrap()

export default bootstrap

music.test.ts

import request from 'supertest'
import bootstrap from '../index'

describe('musics', () => {

    it('should search the musics', async () => {

        const { DI, app } = await bootstrap()
    request(app)
        .get('/musics')
        .expect(200)
        .end()

    await DI.orm.close()

})

})

我的意思是,我想在所有测试结束后关闭连接,但我不能这样做,因为 ORM 连接是由函数 bootstrap 返回的,只能在“it”范围内调用。

谁能帮我做这样的事情?

describe('musics', () => {

    afterAll(async () => {
        await DI.orm.close()
    })

    it('should search the musics', async () => {

        const { DI, app } = await bootstrap()

        request(app)
            .get('/musics')
            .expect(200)
            .end()

    })

})

存储库是:https://github.com/brenomacedo/g-track/tree/master/backend

【问题讨论】:

    标签: typescript rest express jestjs mikro-orm


    【解决方案1】:

    使用beforeAll钩子创建连接,并将结果存储在外部作用域中:

    describe('musics', () => {
    
        let context: any = {}; // TODO type this properly
    
        beforeAll(async () => {
            context = await bootstrap()
        })
    
        afterAll(async () => {
            await context.DI.orm.close()
        })
    
        it('should search the musics', async () => {
            request(context.app)
                .get('/musics')
                .expect(200)
                .end()
    
        })
    
    })
    

    【讨论】:

    • 嘿,谢谢,它解决了我的问题,但 jest 仍然抛出消息“Jest 在测试运行完成后一秒钟没有退出。”,就像连接没有关闭一样。你知道为什么会这样吗?
    • afaik jest v27 做到了这一点,这可能是一个误报警告或 jest 问题,与 v26 一样,它工作得很好(至少它在 orm 测试中是这样)
    猜你喜欢
    • 2013-11-12
    • 1970-01-01
    • 2012-08-28
    • 2012-07-26
    • 2020-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多