wmonk/create-react-app-typescript

import returns undefined when running tests

Closed this issue · 3 comments

Is this a bug report?

Yes

Can you also reproduce the problem with npm 4.x?

Yes

Which terms did you search for in User Guide?

test jest import require undefined

Environment

  1. npm ls react-scripts-ts (if you haven’t ejected): 2.16.0
  2. node -v: v9.7.1
  3. npm -v: 4.6.1 (also 6.1.0)
  4. yarn --version (if you use Yarn): 1.5.1
  5. npm ls react-scripts-ts (if you haven’t ejected): 2.16.0

Then, specify:

  1. Operating system: macOS Sierra 10.12.4
  2. Browser and version (if relevant): not relevant, the problem is when running tests

Steps to Reproduce

  1. create an app as normal and run tests
create-react-app my-app --scripts-version=react-scripts-ts
cd my-app
git init .
yarn
yarn test
  1. add lodash as a dependency and run tests
yarn add lodash
  1. import lodash in App.jsx and try to call a function on it
import _ from 'lodash';
const foo = _.join(['f', 'oo']);
  1. Run tests.
yarn
yarn test

Expected Behavior

Test should pass.

Actual Behavior

Test suite fails to run:

TypeError: Cannot read property 'join' of undefined

Reproducible Demo

https://github.com/bagilevi/cra-ts-import

Relevant diff:
bagilevi/cra-ts-import@3b986a0

Notes

If I use const _ = require('lodash') the tests pass, but then yarn start says "require statement not part of an import statement".

If I try import _ = require('lodash'), I get "Import assignment cannot be used when targeting ECMAScript modules. Consider using 'import * as ns from "mod"', 'import {a} from "mod"', 'import d from "mod"', or another module format instead.".

If I rename foo.ts to foo.js, the test passes, so the problem seems to be TypeScript-related.

I had the same issue trying to import pouchdb, so it's not just lodash, and they both work in the browser.

Any advice would be appreciated, I just recently started using TypeScript. Thank you.

Solution:

-import _ from 'lodash';
+import * as _ from 'lodash';

Thanks @bagilevi - easy fix. Out of curiosity, would you be able to explain to me why this behavior differs between start and test? The original syntax import _ from 'lodash' behaves fine in the start context.

@mcmonster I don't really know, sorry. I gave up on TypeScript due to frustration.