shelfio / jest-dynamodb

Jest preset for DynamoDB local server
MIT License
181 stars 38 forks source link

How can I use `jest-dynamodb` in a `nx` managed monorepo? #217

Open zhaoyi0113 opened 11 months ago

zhaoyi0113 commented 11 months ago

I have a monorepo managed by nx. Each package in this repo references the jest config file from repo root directory. I need to use @shelf/jest-dynamodb to support running dynamodb local for test cases. (https://github.com/shelfio/jest-dynamodb)

One of the package is under packages/is-even/jest.config.js like below:

import path from 'path';

/* eslint-disable */
process.env.JEST_DYNAMODB_CONFIG = path.resolve(__dirname, './jest-dynamodb-config');

console.log('JEST_DYNAMODB_CONFIG:', process.env.JEST_DYNAMODB_CONFIG);

export default {
  displayName: 'is-even',
  preset: '../../jest.preset.js',
};

the root level jest.preset.js is:

module.exports = {
  preset: '@shelf/jest-dynamodb',
  testMatch: ['**/?(*.)+(spec|test).[jt]s?(x)'],
  resolver: '@nx/jest/plugins/resolver',
  moduleFileExtensions: ['ts', 'js'],
  transform: { '^.+\\.(ts|js|html)$': ['ts-jest', [Object]] },
  testEnvironment: 'node',
  testEnvironmentOptions: { customExportConditions: ['node', 'require', 'default'] },
  testTimeout: 5000,

when running the test case, the local dynamodb instance is not launched. Is there a way to make it work with monorepo?

vladholubiev commented 11 months ago

Unfortunately, I do not have experience with nx. Maybe somebody from the community could help here.

ddiprose commented 3 months ago

I got it working with nx using the following:

In your project's jest.config.ts file write:

const jestDynamodbPreset = require('@shelf/jest-dynamodb/jest-preset');

export default {
  passWithNoTests: true,
  displayName: 'yourapp',
  preset: '../../jest.preset.js',
  ...jestDynamodbPreset,
  testEnvironment: 'node',
  transform: {
    '^.+\\.[tj]s$': ['ts-jest', { tsconfig: '<rootDir>/tsconfig.spec.json' }],
  },
  moduleFileExtensions: ['ts', 'js', 'html'],
  ...
};

And in your root's jest.preset.js write:

const nxPreset = require('@nx/jest/preset').default;
const path = require('path');

process.env.JEST_DYNAMODB_CONFIG = path.resolve(__dirname, './jest-dynamodb-config');

module.exports = {
  ...nxPreset,
};

Then in the root create a new file jest-dynamodb-config.ts:

module.exports = {
  tables: [],
  installerConfig: {
      // unrelated but I was using this archive
      downloadUrl: 'https://s3-us-west-2.amazonaws.com/dynamodb-local/dynamodb_local_2023-06-09.tar.gz',
    },
  options: ['-inMemory'],
  port: 8000,
};

This setup also works with the vscode-jest-runner vscode extension out of the box.