"phoenix" 1.6.0 NPM package cannot be imported in jest

I am using a Github Actions build where in parallel I build JavaScript assets and test them, and also Elixir assets.

For that reason, the project is using the packages published to npmjs.org and not the packages loaded from “deps”. My apps/ui/assets/package.json relevant entries look like this:

  "dependencies": {
    "phoenix": "^1.6.0",
   "jest": "^27.0.0"

While the project builds with webpack properly, I have a problem running tests with Jest. it cannot import things from “phoenix” package and crashes like this:

  ● Test suite failed to run

    Cannot find module 'phoenix' from 'js/app/client.js'

    Require stack:

      1 | import "unfetch/polyfill";
      2 |
    > 3 | import { Socket as PhoenixSocket } from "phoenix";

Version 1.5.9 worked fine in both Jest and with Webpack.

I have tried Node versions 12-16, no change, I think Jest for some reason cannot load “phoenix” package but I don’t understand how to fix this.


Phoenix switched to publishing esm files for bundlers. Maybe jest has problems with that.


Yes, I think that’s right.

Phoenix is now being built as ESM package: Switch to esbuild, package js as ESM by mveytsman · Pull Request #4372 · phoenixframework/phoenix · GitHub

and, while Webpack can understand them, Jest doesn’t seem to understand them just yet, not properly at least.

There’s an ongoing discussion on Jest on how to support it, and people provided a number of workarounds but so far no joy for me: Support package exports in `jest-resolve` · Issue #9771 · facebook/jest · GitHub


You might be able to still use the old import by doing something like "phoenix/priv/static/phoenix.js" for import.

What have people been doing about this? I have a new application and want to write tests for the React portion, I originally installed Jest but ran into this issue. Are there other test runners that work here?

Actually, installing the npm package seems to work for me. I installed it as a dev dependency because it’s only for making tests work, but it gets past that error now (and the local server still works as expected). In this case, I’m not sure what problem you were encountering @hubertlepicki, but I hope you were able to figure something out.

@gpreston I have sent a PR to Phoenix itself here: https://github.com/phoenixframework/phoenix/pull/4512

AFAIK the fix still works and I am able to import “phoenix” still and run Jest tests. We also use it with React. Let me know if you have problems.

1 Like