Can't use v8 in Jest unit tests
See original GitHub issueI am using TypeScript, Jest and Webpack in my project. I upgraded to v8 and now I can’t use react-waypoint
in my unit tests anymore.
With v7 I imported this library with
import * as Waypoint from 'react-waypoint';
Now with v8 I have to import it like
import Waypoint from 'react-waypoint';
With that default import it runs with TypeScript and Webpack as expected but not in my unit tests that run with Jest. If I change the import to the v7 import * as Waypoint
syntax TypeScript and Webpack fails, but Jest runs fine.
I believe it has something to do how this library is exported in the package because in Jest I transpile everything to CommonJS (because Node only understands CommonJS) but then there is a .default
import which doesn’t exist. In Webpack I transpile everything to ESM import syntax and TypeScript take the default export and Webpack can handle that.
My Workaround at the moment is to use v7 instead of v8 because there everything works out of the box.
Maybe this is related to #238? 🤔
Issue Analytics
- State:
- Created 6 years ago
- Reactions:2
- Comments:10 (1 by maintainers)
Not really. We don’t have any technical issues. We just dropped support for default exports because they can be difficult to maintain, refactor and their semantic could change without knowing it. Furthermore you don’t know what you really import. For example
import foo from 'mylib'
compared toimport { calculateDistance } from 'mylib'
. And we are not alone with this opinion 😉But this has nothing to do with this issue. When I import
react-waypoint
8.0.1 in my TypeScript project like thatIt gives me the component when I bundle everything with webpack but
undefined
when I run my unit tests with Jest.After a little bit debugging I believe I found out what’s going on: in your package.json you have
defined. That’s cool. Webpack respects that and uses
es/index.js
. The TypeScript definition is also for the ESM file. Now when I run my tests with Jest, Jest usescjs/index.js
instead ofes/index.js
. What now happens is that TypeScript adds a.default
:TypeScript
gets transpiled to
But there is no
.default
. If you had named exports it would look like this:gets transpiled to
and then it should work. I also found some issues / PR’s in the Jest repository like this https://github.com/facebook/jest/issues/4842 or that https://github.com/facebook/jest/pull/5485
So I found the problem but don’t have a solution 😁 Except “change your default export to a named export” or “only use CommonJS for your package”.
Thanks for the explanation.
I got around this by creating a jest mock of waypoint that exports default.
So in
__mocks__
I created a filereact-waypoint.js
withBit dirty, but does the job for now