wessberg / DI-compiler

A Custom Transformer for Typescript that enables compile-time Dependency Injection
MIT License
82 stars 7 forks source link

Jest example #10

Open vladmelnikov opened 3 years ago

vladmelnikov commented 3 years ago

Thank you for library its awesome. But i ran into issue cant configure with jest. Can you please provide example how to setup with jest ts-jest

ZettZet commented 1 year ago

Three years later, this question will be answered:) It may no longer be relevant to you, I guess, but somebody will find it helpful.

There are two main points to connect di-compiler to ts-jest:

  1. let ts-jest know about transformer
  2. implement a transformer

let's start with the second one

import type { DiOptions } from '@wessberg/di-compiler'
import { di } from '@wessber/di-compiler'
import type { TsCompilerInstance } from 'ts-jest/dist/types'

export const version = 1
export const name = '@wessberg/di-compiler'

type Options = {
  isAfter?: boolean
}

export function factory(compilerInstance: TsCompilerInstance, options?: Options) {
  const typescript = compilerInstance.configSet.compilerModule

  const config: DiOptions = {
    program: compilerInstance.program,
    typescript: ts
  }

  const { before, after } = di(config)
  if (options?.isAfter) {
    return after?.[0]
  }

  return before?.[0]
}

After that we can add this transformer to jest.config.js:

/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
  transform: {
    '^.+\\.[tj]sx?$': [
      'ts-jest',
      {
        astTransformers: {
          before: [{ path: 'relative path to transformer file' }],
          after: [{ path: 'relative path to transformer file', options: { isAfter: true } }],
        }
      }
    ]
  }
  /* Rest of your config */
}

Maybe there is a better way to deal with it, but it worked for me. I hope it helps someone.