Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do testing with Jest and Knex in TypeScript?

I'm trying to test GraphQL server with Jest and Knex. I had a hard time figuring out how to use knexfile in typescript. But now everything is working fine for development and production envs, except for testing.

Here's my current 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;

This is global setup for 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);
  }
};

This is global teardown:

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

It keeps giving me error:

Unhandled rejection SyntaxError: Unexpected token *
/home/my/knex-graphql/migration/20190821235716_create_user.ts:1
import * as Knex from 'knex';
       ^

SyntaxError: Unexpected token *
    at Module._compile (internal/modules/cjs/loader.js:872:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:947:10)
    at Module.load (internal/modules/cjs/loader.js:790:32)
    at Function.Module._load (internal/modules/cjs/loader.js:703:12)
    at Function.<anonymous> (/home/my/knex-graphql/node_modules/@sentry/node/src/integrations/console.ts:37:43)
    at Function._load (/home/my/knex-graphql/node_modules/@sentry/node/src/integrations/http.ts:73:43)
    at Module.require (internal/modules/cjs/loader.js:830:19)
    at require (internal/modules/cjs/helpers.js:68:18)
    at FsMigrations.getMigration (/home/my/knex-graphql/node_modules/knex/lib/migrate/sources/fs-migrations.js:84:12)
    at /home/my/knex-graphql/node_modules/knex/lib/migrate/Migrator.js:82:69
    at arrayFilter (/home/my/knex-graphql/node_modules/lodash/lodash.js:582:11)
    at filter (/home/my/knex-graphql/node_modules/lodash/lodash.js:9173:14)
    at /home/my/knex-graphql/node_modules/knex/lib/migrate/Migrator.js:81:13
    at tryCatcher (/home/my/knex-graphql/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (/home/my/knex-graphql/node_modules/bluebird/js/release/promise.js:517:31)
    at Promise._settlePromise (/home/my/knex-graphql/node_modules/bluebird/js/release/promise.js:574:18)
From previous event:
    at Migrator.latest (/home/my/knex-graphql/node_modules/knex/lib/migrate/Migrator.js:71:8)
    at /home/my/knex-graphql/test/global/setup.ts:24:32
    at Generator.next (<anonymous>)
    at fulfilled (/home/my/knex-graphql/test/global/setup.ts:5:58)
    at processTicksAndRejections (internal/process/task_queues.js:85:5)

Tech stack: Apollo-server-express, TypeScript, Knex.js, PostgreSQL, Jest

like image 733
Rario Avatar asked Sep 23 '19 11:09

Rario


People also ask

Can you write jest tests in TypeScript?

Via ts-jest ​ts-jest is a TypeScript preprocessor with source map support for Jest that lets you use Jest to test projects written in TypeScript. In order for Jest to transpile TypeScript with ts-jest , you may also need to create a configuration file.

How do you test express routes with jest TypeScript?

Initialize project and import the imports Create a directory for your project and cd into it. Use NPM to initialize the project npm init -y . Import dependencies npm i express . Import dev-dependencies npm i --save-dev typescript supertest nodemon jest ts-jest ts-node @types/jest @types/supertest @types/express .

Can you do integration testing with jest?

Jest is a popular unit test framework that can easily be extended to include integration tests.


1 Answers

You need to add ts-jest, which will transpile your ts files for jest. Install it

npm install --save-dev ts-jest

Add default ts-jest config

npx ts-jest config:init
like image 61
felixmosh Avatar answered Oct 05 '22 23:10

felixmosh