Typeorm连接“默认";在jest globalSetup中创建连接时找不到 [英] Typeorm Connection "default" was not found when connection is created in jest globalSetup

查看:198
本文介绍了Typeorm连接“默认";在jest globalSetup中创建连接时找不到的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的问题与#5164 这个问题.考虑以下工作测试代码:

I'm having a similar problem as in #5164 and this question. Consider the following working test code:

// AccountResolver.test.ts
describe('Account entity', () => {
  it('add account', async () => {
    await createConnections()
    const defaultConnection = getConnection('default')

    const actual = await callGraphql(
      `mutation {
        addAccount(options: {
          accountIdentifier: "7csdcd8-8a5f-49c3-ab9a-0198d42dd253"
          name: "Jake, Bob (Braine-l’Alleud) JAM"
          userName: "Bob.Marley@contoso.com"
        }) {
          accountIdentifier
          name
          userName
        }
      }`
    )
    expect(actual.data).toMatchObject({
      data: {
        addAccount: {
          accountIdentifier: '7csdcd8-8a5f-49c3-ab9a-0198d42dd253',
          name: 'Jake, Bob (Braine-l’Alleud) JAM',
          userName: 'Bob.Marley@contoso.com',
        },
      },
    })

    await defaultConnection.query(`DELETE FROM Account`)
    await defaultConnection.close()
  })
})

创建连接并关闭连接的代码应在所有测试之前和所有测试完成之后执行,这就是为什么我们将其添加到globalSetup.tsglobalTeardown.ts的原因:

The code to create a connection and close it should be executed before all tests and after all tests are done, that's why we've added it to globalSetup.ts and globalTeardown.ts:

// globalSetup.ts
require('ts-node/register')
import { createConnections } from 'typeorm'

module.exports = async () => {
  // console.log('jest setup')
  await createConnections()
}

// globalTeardown.ts
require('ts-node/register')
import { getConnection } from 'typeorm'

module.exports = async () => {
  const defaultConnection = getConnection('default')
  await defaultConnection.close()
}

// AccountResolver.test.ts
describe('Account entity', () => {
  it('add account', async () => {
    const defaultConnection = getConnection('default')
    await defaultConnection.query(`DELETE FROM Account`)

    const actual = await callGraphql(
      `mutation {
        addAccount(options: {
          accountIdentifier: "7csdcd8-8a5f-49c3-ab9a-0198d42dd253"
          name: "Jake, Bob (Braine-l’Alleud) JAM"
          userName: "Bob.Marley@contoso.com"
        }) {
          accountIdentifier
          name
          userName
        }
      }`
    )
    expect(actual.data).toMatchObject({
      data: {
        addAccount: {
          accountIdentifier: '7csdcd8-8a5f-49c3-ab9a-0198d42dd253',
          name: 'Jake, Bob (Braine-l’Alleud) JAM',
          userName: 'Bob.Marley@contoso.com',
        },
      },
    })
  })
})

在两个文件中省略行require('ts-node/register')会引发此错误:

Omitting the line require('ts-node/register') from both files throws this error:

T:\ Test \ src \ it-portal \ entity \ Account.ts:1 进口 { ^^^^^^ SyntaxError:无法在模块外部使用import语句

T:\Test\src\it-portal\entity\Account.ts:1 import { ^^^^^^ SyntaxError: Cannot use import statement outside a module

使require行保持抛出状态:

FAIL src/resolvers/AccountResolver.test.ts×添加帐户(31毫秒)● 帐户实体›添加帐户ConnectionNotFoundError:连接 找不到默认".帐户实体

FAIL src/resolvers/AccountResolver.test.ts × add account (31 ms) ● Account entity › add account ConnectionNotFoundError: Connection "default" was not found.Account entity

版本

    "jest": "^26.0.1",
    "ts-jest": "^26.1.0",
    "ts-node-dev": "^1.0.0-pre.44",
    "typescript": "^3.9.5"

配置

// jest.config.js
module.exports = {
  preset: 'ts-jest',
  globalSetup: './src/test-utils/config/globalSetup.ts',
  globalTeardown: './src/test-utils/config/globalTeardown.ts',
  setupFiles: ['./src/test-utils/config/setupFiles.ts'],
  moduleDirectories: ['node_modules', 'src'],
  globals: {
    'ts-jest': {
      tsConfig: 'tsconfig.json',
      diagnostics: {
        warnOnly: true,
      },
    },
  },
  coverageThreshold: {
    global: {
      branches: 80,
      functions: 80,
      lines: 80,
      statements: 80,
    },
  },
  coverageReporters: ['json', 'lcov', 'text', 'clover'],
}

感谢您指出我的错误.当我是新手时,我尝试使用谷歌搜索功能,但是如果这不是我也不了解该工具还是其中一个错误,则找不到真正的答案.在此处找到了类似的问题,并带有

Thank you for pointing out my mistakes. As I'm new I tried googling but couldn't really find an answer if this is me not understanding the tool or a bug in the too. Found a similar issue here with a PR.

似乎测试在完全隔离的环境中运行,在这些环境中,它们无法访问在globalSetup中设置的连接.

It seems like the tests are running in a fully isolated environment where they can't access the connection set up within globalSetup.

到目前为止,我发现的唯一解决方法是将以下代码添加到每个测试文件中:

The only workaround I have found thus far is to add the following code to every test file:

beforeAll(async () => {
  await createConnections()
})

afterAll(async () => {
  const defaultConnection = getConnection('default')
  await defaultConnection.close()
})

推荐答案

require('ts-node/register')不应出现在.ts文件中.它们已经由TypeScript编译器处理.

require('ts-node/register') shouldn't present in .ts files. They are already processed by TypeScript compiler.

这不是globalSetupglobalTeardown的用途.它们在Jest父进程中运行,并被评估一次,而每个测试套件在子进程中运行.

This is not what globalSetup and globalTeardown are for. They run in Jest parent process and are evaluated once, while each test suite runs in child processes.

这可以通过在 setupFilesAfterEnv 中提供通用设置来实现选项:

This can be achieved by providing a common setup in setupFilesAfterEnv option:

// jest.setup.ts
...
beforeAll(async () => {
  await createConnections()
})

afterAll(async () => {
  const defaultConnection = getConnection('default')
  await defaultConnection.close()
})

由于Jest测试并行运行,因此将导致多个数据库连接.如果由于连接限制而不希望这样做,则需要使用Jest runInBand选项.

Since Jest tests run in parallel, this will result in multiple database connections. If this is not desirable because of connection limit, Jest runInBand option needs to be used.

不需要所有测试的设置,因为并非所有测试套件都需要数据库连接,而它们将无条件地占用时间并占用数据库连接池.在这种情况下,可以在使用数据库而不是setupFilesAfterEnv的测试中直接导入jest.setup.ts,而无需在每个套件中指定beforeAllafterAll.

A setup for all tests not desirable because not all test suites need database connection, while they will unconditionally take time and occupy database connection pool. In this case jest.setup.ts can be imported directly in tests that use a database instead of setupFilesAfterEnv, no need to specify beforeAll and afterAll in each suite.

这篇关于Typeorm连接“默认";在jest globalSetup中创建连接时找不到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆