如何在 TypeScript 中使用 Jest 和 Knex 进行测试?

Rar*_*rio 8 javascript node.js typescript knex.js jestjs

我正在尝试使用 Jest 和 Knex 测试 GraphQL 服务器。我很难弄清楚如何在打字稿中使用 knexfile。但是现在除了测试之外,开发和生产环境一切正常。

这是我的当前knexfile.ts

// knexfile.ts

const defaults = {
  client: 'pg',
  connection: {
    host: DB_HOST,
    user: DB_USER,
    password: DB_PASSWORD,
    database: DB_DATABASE
  },
  pool: {
    min: 2,
    max: 10
  },
  migrations: {
    extension: 'ts',
    directory: './migration',
    tableName: 'knex_migrations'
  },
  seeds: {
    extension: 'ts',
    directory: './seed'
  }
};

interface KnexConfig {
  [key: string]: object;
}

const knexConfig: KnexConfig = {
  local: {
    client: 'sqlite3',
    connection: {
      filename: './dev.sqlite3'
    }
  },

  development: {
    ...defaults,
    debug: true,
    useNullAsDefault: true
  },

  production: {
    ...defaults
  }
};

/**
 * `export default` does not work, causes `client` missing problem
 * at database migration.
 */
export = knexConfig;
Run Code Online (Sandbox Code Playgroud)

这是 Jest 的全局设置:

// globalSetup.ts

export = async () => {
  try {
    // Start http server
    await httpServer.listen(PORT);

    // Rollback and migrate
    // await knex.migrate.rollback().then(() => knex.migrate.latest());
    knex.migrate.latest();
  } catch (err) {
    // Log the error
    logger.error('', err);
  }
};
Run Code Online (Sandbox Code Playgroud)

这是全局拆解:

// globalTeardown.ts

export = async () => {
  try {
    await knex.migrate.rollback();

    // Shutdown server
    httpServer.close(() => logger.info('Server closed'));
  } catch (err) {
    // Log the error
    logger.error('', err);
  }
};
Run Code Online (Sandbox Code Playgroud)

它不断给我错误:

// knexfile.ts

const defaults = {
  client: 'pg',
  connection: {
    host: DB_HOST,
    user: DB_USER,
    password: DB_PASSWORD,
    database: DB_DATABASE
  },
  pool: {
    min: 2,
    max: 10
  },
  migrations: {
    extension: 'ts',
    directory: './migration',
    tableName: 'knex_migrations'
  },
  seeds: {
    extension: 'ts',
    directory: './seed'
  }
};

interface KnexConfig {
  [key: string]: object;
}

const knexConfig: KnexConfig = {
  local: {
    client: 'sqlite3',
    connection: {
      filename: './dev.sqlite3'
    }
  },

  development: {
    ...defaults,
    debug: true,
    useNullAsDefault: true
  },

  production: {
    ...defaults
  }
};

/**
 * `export default` does not work, causes `client` missing problem
 * at database migration.
 */
export = knexConfig;
Run Code Online (Sandbox Code Playgroud)

技术栈:Apollo-server-express、TypeScript、Knex.js、PostgreSQL、Jest

fel*_*osh 1

您需要添加ts-jest,它将把您的 ts 文件转译为 jest。安装它

npm install --save-dev ts-jest
Run Code Online (Sandbox Code Playgroud)

添加默认 ts-jest 配置

npx ts-jest config:init
Run Code Online (Sandbox Code Playgroud)