Back to all posts
2 min read

When Jest Can't Find Your Damn Imports

jest testing javascript typescript debugging
When Jest Can't Find Your Damn Imports

When Jest Can’t Find Your Damn Imports

So there I was, running my tests like a good developer, and Jest just… couldn’t find anything. Error after error about modules not being found. You know that feeling when everything should work, but it just doesn’t?

The thing is, my code worked perfectly fine. The imports were right there. I could see them. VS Code could see them. TypeScript was happy. But Jest? Nah, Jest was having none of it.

The “But It’s Right There” Problem

Here’s what was driving me crazy. I had this beautiful path alias setup, something like:

import { EmailListModel } from "@database/models/email-list-exclusive-team.model";

Clean, right? No messy relative paths with a million ../../ going on. Just a nice @database alias pointing to my database folder.

Except Jest was like “What’s @database? Never heard of it.”

And I’m sitting there thinking, “Dude, it’s literally in my tsconfig. It’s RIGHT THERE.”

The Facepalm Moment

Turns out, Jest doesn’t care about your tsconfig path mappings. At all. It’s doing its own thing, living its best life, completely ignoring all the configuration you carefully set up.

So even though TypeScript knew exactly where @database pointed to, Jest was just blindly looking for a package called @database in nodemodules and going ”¯\_(ツ)/¯ not found.”

The Fix That Should Be Obvious But Isn’t

The solution? You gotta tell Jest about your path aliases. Again. Separately. Because why would it just use the config that already exists, right?

In your package.json (or jest.config.js if you’re fancy), you need to add a moduleNameMapper:

{
  "jest": {
    "moduleNameMapper": {
      "^@database/(.*)$": "<rootDir>/src/database/$1"
    }
  }
}

That little regex is basically saying “Hey Jest, when you see @database, just look in src/database instead of freaking out.”

Why This Keeps Happening

I’ve hit this issue like three times now on different projects. Every time I set up path aliases, I configure TypeScript, everything works in development, and then I write my first test and… boom. Same error.

You’d think I’d remember by now, but nope. Each time I’m convinced it’s something else. Maybe the test file is wrong? Maybe I broke something? Nah, it’s always the moduleNameMapper.

The Takeaway

If Jest can’t find your imports but everything else can, check your moduleNameMapper in your Jest config. Odds are you just need to map your path aliases there too.

It’s one of those things that feels obvious after you know it, but the first time it happens you’re just confused why your perfectly valid imports are suddenly broken.

Anyway, tests are green now. Until the next time I forget about this and spend 20 minutes debugging the same issue again.