Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using jest + typescript in monorepo

I'm currently trying to use jest in a Typescript monorepo (not Lerna or anything just baseURL and paths, also, not my decision) and one of the files I'm testing imports a something from the monorepo.


import {publish, subscribe} from "message-bus"

Now in my tsconfig.json I have:

...
    "compilerOptions": {
        "baseUrl": "./packages",
        "paths": {
            "message-bus":["message-bus/src"],
        }, 
...

and in the package jest.config.js:

module.exports = {
...
  preset: 'ts-jest',
  moduleNameMapper: {
    '^message-bus/(.*)$': "../message-bus/src/$1"
  }
...
}

Even with all this in place jest complains that it cannot find the module message-bus. Can you please help me fix my configuration?

like image 717
yorodm Avatar asked Oct 23 '25 09:10

yorodm


1 Answers

Presuming that your jest.config.js is at the root of your package and not the monorepo, you need the moduleNameMapper to form a path that can be understood from any location. You do this by starting with the directory that the jest.config.js file is in and then building your path from there. This will create an absolute path to your mapped module.

Also, you need the slash (/) in your regex capture group because it's not always in the path.

const path = require('path');

module.exports = {
  ...
  preset: 'ts-jest',
  moduleNameMapper: {
    '^message-bus(.*)$': path.join(__dirname, '../message-bus/src$1')
  }
  ...
}
like image 167
robdonn Avatar answered Oct 25 '25 06:10

robdonn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!