簡體   English   中英

可以在外部函數/文件中重構 hook function 嗎?

[英]Possible to refactor hook function in external function/file?

我非常喜歡 DRY 概念。 我的 nestJS 應用程序中的 e2e 測試始終使用相同的beforeAllafterAll掛鈎 - 除了更改一個模塊。 我想將這些鈎子放在另一個函數/文件中。 但是這樣做我會盡可能地放松app的上下文。

describe('AnyModule', () => {
  let app

  beforeAll(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
        imports: [
        AnyModule,
        DatabaseModule,
        GraphQLModule.forRoot({
            typePaths: ['./**/*.graphql']
        })
        ]
    }).compile()

    app = moduleFixture.createNestApplication()
    await app.init()
  })
  afterAll(async () => {
    await app.close()
  })

  test('', () => {
    return request(app.getHttpServer())
  })
})

我想過這樣的事情:

const beforeHook = async (app, Module) => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
        imports: [
        Module,
        DatabaseModule,
        GraphQLModule.forRoot({
            typePaths: ['./**/*.graphql']
        })
        ]
    }).compile()

    app = moduleFixture.createNestApplication()
    await app.init()
    return app
}

這叫做像

let app
beforeAll(async () => beforeHook(app, AnyModule))
afterAll(async () => await app.close())

test('', () => {
    return request(app.getHttpServer())
})

但它返回錯誤TypeError: Cannot read property 'getHttpServer' of undefined

您將 moduleFixture.createNestApplication() 分配給應用程序的方式就在 function 的 scope 中。不在外面。 看這里為什么: https://www.javascripttutorial.net/javascript-pass-by-value/

但是您也已經返回了應用程序。 所以只要改變

beforeAll(async () => beforeHook(app, AnyModule))

beforeAll(async () => {
  app = await beforeHook(app, AnyModule)
})

它應該工作正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM