Member-only story
Jest encountered an unexpected token
Hey fellow developers, if you’re reading this, you’re probably getting this juicy error when running your unit tests with Jest: Jest encountered an unexpected token.
You probably asked ChatGPT, tried the solution, and realized it was bullshit.
This usually means that in your module which you are writing a unit test for, you are using something, perhaps a method from a external dependency, and that dependency is using ES Module
and Jest does not transpile
code from node_modules
. In above error within the Details section, you can see which package(s) having this problem.
let’s say the package that does have this problem and you see in the above error within the Details
is called: @oldbutawesome/tony
and you are importing something in your module from it, let’s say a method called whoIsAwesome()
The best and perhaps the easiest way to fix this problem, is to mock it
jest.mock('@oldbutawesome/tony', () => ({
whoIsAwesome: jest.fn(),
}))
Simple as that, but if you don’t want to mock it for whatever reasons, there’s one other thing you can do, to update your test script in your package json to contain the following: