Jest fails to parse TSX in preact - jestjs

I'm trying to run tests with Jest and enzyme in a Preact app with TypeScript.
I get a Jest encountered an unexpected token error :
FAIL src/app/app.test.tsx
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse,
e.g. it's not plain JavaScript.
...
Details:
src/app/app.test.tsx:10
const wrapper = enzyme_1.mount(<app_1.default optOutUrl="none"/>);
^
SyntaxError: Unexpected token <
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1059:14)
After seen TypeScript example in this repository, I Changing jsx option to react in tsconifg.json. But It not helpful for my project environment:
Cannot find module 'react' from 'styled.js'
However, Jest was able to find:
'./styled.js'
'./styled.js.flow'
'./styled.js.map'
See https://jestjs.io/docs/en/configuration#modulefileextensions-array-string
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:276:11)
at Object.<anonymous> (node_modules/linaria/src/react/styled.js:3:15)
In the above error, it says that react parsing failed in the styled component related file. (I’m use styled components from linaria/react with custom Preact typing.) this issue not appear in development and production environment.
I also tried using babel-jest with below config.
“transform”: {
“^.+\\.t(s|x)$”: “babel-jest”
}
FAIL src/app/app.test.tsx
● Test suite failed to run
src/app/app.tsx: Cannot find module 'react'

Related

Jest Cannot find module 'cls-hooked'

I try to implement e2e tests in a simple NestJS project (generate with 'nest new' command, add some dependencies and config Project here), the existing tests (not e2e ones) run properly (all modules are resolved).
But, when I execute the default app.e2e-spec.ts (generated by nest cli), I got this following error
Cannot find module 'cls-hooked' from 'src/common/http-context.ts'
The only difference between working and broke version is the test file selected (in the jest config)
testRegex: '.e2e-spec.ts$', // Doesn't work
// testRegex: '.*\\.spec\\.ts$', // Work
The module resolution with TS works well when I look for the trace of tsc --traceResolution
The project is running correctly and works well. Then, globally, Jest & TS are well configured
The error is the same when I use a relative path
// src/common/http-context.ts
// import * as cls from 'cls-hooked';
import * as cls from '../../node_modules/#types/cls-hooked';
When I explicitly set the path to module
moduleNameMapper: {
'cls-hooked': '<rootDir>/node_modules/#types/cls-hooked/index.d.ts',
},
The error suggest an interoperability issue
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
C:\Users\taquet_p\Sources\nestJsGrapQLTest\test-jest-imports\node_modules\#types\cls-hooked\index.d.ts:8
import { EventEmitter } from 'events';
^^^^^^
SyntaxError: Cannot use import statement outside a module
> 1 | import * as cls from 'cls-hooked';
| ^
2 |
3 | export class HttpContext {
4 |
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
at Object.<anonymous> (src/common/http-context.ts:1:1)
I tried to configure support for ECMAScript module and other things in tsconfig.json and jest.config.js
I check most of SOF questions about Cannot find module within Jest
I have no more ideas to googling about.
Do anyone has a solution ? A suggestion ?
The github repo provide the atomic project to reproduce the issue directly. Just pull, npm install & run test (the jest config file is a bit dirty :-) )

create-react-app and jest - Cannot use import statement outside a module

I am using create-react-app. Running jest from the CLI causes this error (though in VS Code it shows in my test file that my test passes):
(base) ➜ component-library git:(setup) ✗ jest
FAIL src/App.test.js
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
/Users/Me/go/src/gitlab.com/tensile-payments/component-library/src/setupTests.js:5
import '#testing-library/jest-dom';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
My setupTests.js file looks like this:
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '#testing-library/jest-dom';
import Enzyme from 'enzyme';
import Adapter from '#wojtekmaj/enzyme-adapter-react-17';
Enzyme.configure({ adapter: new Adapter() });
I understand from another question's answer that Jest Babel-transforms files before running tests, which should get rid of these import statements. I haven't ejected and so haven't changed the babel config. Other people had the issue that node modules weren't being transformed because the default config excludes them, but this error isn't coming from a node module. How can I fix this?
I fixed it by running tests with npm run test instead of jest, as well as removing
"jest": {
"setupFilesAfterEnv": [
"<rootDir>src/setupTests.js"
]
}
from my package.json (though Enzyme instructs to include it when using Jest).

How to run jest tests in SPFx when importing #microsoft/sp-core-library?

The below error occurs when running npm test in a SharePoint Framework web part with a react component that imports DisplayMode from '#microsoft/sp-core-library':
export { default as _BrowserDetection } from './BrowserDetection';
^^^^^^
SyntaxError: Unexpected token export
Following the resolution steps mentioned in https://github.com/SharePoint/sp-dev-docs/issues/2325#issuecomment-446416878 works fine for testing but fails for the build process.

tests failing with SyntaxError: Unexpected token export

After updating a package "office-ui-fabric-react" from "5.124.0 to "6.128.0", all my tests are failing with following error:
FAIL src\***.test.tsx
● Test suite failed to run
\node_modules\office-ui-fabric-react\lib\Callout.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export * from './components/Callout/index';
^^^^^^
SyntaxError: Unexpected token export
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/ScriptTransformer.js:289:17)
If you are using create-react-app, You probably don't want to eject it.
To solve this without ejecting we need to be able to modify jest configuration without eject.
Luckily there is this library https://github.com/timarney/react-app-rewired
Follow its instruction and install react-app-rewired in you CRA project
Then you need to change your package.json to include "jest" configuration
"jest": {
"moduleNameMapper": {
"office-ui-fabric-react/lib/(.*)$": "office-ui-fabric-react/lib-commonjs/$1"
},
"transformIgnorePatterns": [
"node_modules/(?!office-ui-fabric-react)"
]
}
Resource: https://github.com/OfficeDev/office-ui-fabric-react/wiki/Fabric-6-Release-Notes
Update
The latest create-react-app already support moduleNameMapper and transformIgnorePatterns configuration.
So there are no need to use react-app-rewired anymore.
https://create-react-app.dev/docs/running-tests/#configuration
export is used in ES modules, whereas because Jest is run in Node it requires common JS modules. See the docs on transformIgnorePatterns on how to convert it to common JS with your TypeScript setup.

AVA Test Runner Setup with Create React App Boilerplate

Trying to setup AVA after running create-react-app. There are a few tutorials and references of this gist I've found and tried, but I keep getting an unexpected token error on the JSX <App /> element. Anyone know what is wrong with that gist? Full output of npm run test:
react-with-ava#0.1.0 test /react-with-ava
cross-env NODE_ENV=test ava
1 exception
Uncaught Exception
SyntaxError: /react-with-ava/src/App.test.js: Unexpected token (8:18)
SyntaxError: /react-with-ava/src/App.test.js: Unexpected token (8:18)
6 | test('renders without crashing', t => {
7 | const div = document.createElement('div');
8 | ReactDOM.render(<App />, div);
| ^
9 | });
It is neither supported nor recommended to use Ava with Create React App.
The created project already contains a test runner (Jest) which we recommend to use. Run npm test in the project folder to start.
In theory you could get Ava to work but this would require configuring Babel which will get confusing in a CRA project very quickly. If you insist on using Ava you can npm run eject and then replace Jest with Ava manually in the ejected project.

Resources