tests failing with SyntaxError: Unexpected token export - jestjs

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.

Related

Express application crashes when it is built with webpack

I am trying to use graphql-upload in a typescript express app (graphql api) built with webpack. When I run with ts-node my app works fine. But when I compile with webpack and then run I get a weird error when I try to upload a file.
My setup
Typescript app
Apollo server / Typegraphql
Build with webpack
My Code
(stripped down to the essentials)
https://github.com/ziggy6792/graphql-file-uploads
My Problem
When I run with ts-node yarn start:ts:node then run yarn test an image gets uploaded no problem
But then I build with webpack yarn start then run yarn test I get the following error
/Users/sive/Documents/workspace/graphql-file-uploads/dist/index.js:56105
if (!isObject(operations) && !Array.isArray(operations))
^
TypeError: isObject is not a function
at Busboy.<anonymous> (/Users/sive/Documents/workspace/graphql-file-uploads/dist/index.js:56105:18)
at Busboy.emit (node:events:378:20)
at Busboy.module.exports../node_modules/busboy/lib/main.js.Busboy.emit (/Users/sive/Documents/workspace/graphql-file-uploads/dist/index.js:32204:33)
at PartStream.onEnd (/Users/sive/Documents/workspace/graphql-file-uploads/dist/index.js:32528:15)
at PartStream.emit (node:events:390:22)
at Dicer.onPart (/Users/sive/Documents/workspace/graphql-file-uploads/dist/index.js:32386:13)
at Dicer.emit (node:events:378:20)
at Dicer.module.exports../node_modules/dicer/lib/Dicer.js.Dicer.emit (/Users/sive/Documents/workspace/graphql-file-uploads/dist/index.js:45439:35)
at Dicer.module.exports../node_modules/dicer/lib/Dicer.js.Dicer._oninfo (/Users/sive/Documents/workspace/graphql-file-uploads/dist/index.js:45540:12)
at SBMH.<anonymous> (/Users/sive/Documents/workspace/graphql-file-uploads/dist/index.js:45486:10)
[nodemon] app crashed - waiting for file changes before starting...
My Attempts to solve
I am not sure if this actually a problem with graphql-upload or webpack or something else. I also noticed that my issue looks similar to this issue, but I didn't really understand if there were any fixes to that issue and if indeed it is the same issue I am facing.
I tried to upgrade webpack (branch upgraded-packages) but this made the problem worse as I get this issue when I start the server
TypeError: Cannot read property 'graphql' of undefined
at getPeerDependencyGraphQLRequirement (/Users/sive/Documents/workspace/graphql-file-uploads/dist/index.js:104216:44)
at Object.ensureInstalledCorrectGraphQLPackage (/Users/sive/Documents/workspace/graphql-file-uploads/dist/index.js:104221:32)
at Function.checkForErrors (/Users/sive/Documents/workspace/graphql-file-uploads/dist/index.js:103346:27)
at Function.generateFromMetadataSync (/Users/sive/Documents/workspace/graphql-file-uploads/dist/index.js:103325:14)
at Function.generateFromMetadata (/Users/sive/Documents/workspace/graphql-file-uploads/dist/index.js:103315:29)
at Object.buildSchema (/Users/sive/Documents/workspace/graphql-file-uploads/dist/index.js:103940:61)
at /Users/sive/Documents/workspace/graphql-file-uploads/dist/index.js:99831:41
at Generator.next (<anonymous>)
at /Users/sive/Documents/workspace/graphql-file-uploads/dist/index.js:99819:71
at new Promise (<anonymous>)
Any help would be greatly appreciated.
My best guess at the problem
From reading the linked issue it seems like isObject seems to ship ECMA Script modules with a newer version. Webpack might pick the ES modules version, but this version differs in the sense that the default export is now default and Apollo Server would have to import it as such or call isObject.default. In this changelog they say it might be breaking for users using bundlers.
Your two options now:
You could use yarn force the dependency to a previous version of isobject:
{
...
"resolutions": {
"graphql-file-uploads/isobject": "3.0.1"
}
}
Or you could simply not bundle your app and use TypeScript for building instead. You lose the benefits of bundling, but you are using an environment that is much more common for running node apps. Furthermore you will use TypeScript as a compiler just like ts-node unifying your development and production tooling.
You can compile using TypeScript like this:
yarn tsc 'src/**/*.ts'
In your TSConfig you should configure the output so that it also emits files to /dist.

Jest throwing error, "transformIgnorePatterns is not working"

I am writing the unit tests for my JavaScript/ React JS application using Jest testing framework. When I run my test I am getting the following error.
● 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:
C:\Users\{user}\{project}\app\node_modules\react-date-picker\node_modules\react-calendar\dist\Calendar.css:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.react-calendar {
The error is coming from the package in the node_modules folder, \react-date-picker.
So to fix that, I changed the jest.config.js file as follow.
const esModules = [ 'react-date-picker'].join('|');
module.exports = {
verbose: true,
transformIgnorePatterns: [`/node_modules/(?!${esModules})`]
};
This is the command for the "npm run unit:test"
"jest --watchAll --testPathPattern=tests/unit --config jest.config.js",
When I run the test again, I am still getting the same error. How can I fix it?
A pretty similar case here, he managed to fix it by adding "allowJs": true to the compilerOptions of each lib/app's tsconfig.spec.json (or alternatively to the root tsconfig.json) in addition to setting transformIgnorePatterns.
See source: https://github.com/nrwl/nx/issues/812

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).

Jest fails to parse TSX in preact

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'

Mocha - Running test ReferenceError: regeneratorRuntime is not defined

I am trying to run tests with async/await using mocha. The project architecture was setup before I started working on it and I have been trying to update it's node version to 8.9.4. The project is an isomorphic application and uses babel, gulp and webpack to run.
To run the tests we run a gulp task. There are two .bablerc files in the project. One in the root folder of the project and another in the test fodler.
Both have the same configuration:
{
"presets": [
["env", {"exclude": ["transform-regenerator"]}],
"react",
"stage-1"
],
"plugins": [
"babel-plugin-root-import"
]
}
When I run the app locally there is no error returned anymore. However when I run the tests with gulp test:api I constantly get the error: ReferenceError: regeneratorRuntime is not defined
This is my gulp file in the test folder:
var gulp = require('gulp')
var gutil = require('gulp-util')
var gulpLoadPlugins = require('gulp-load-plugins')
var plugins = gulpLoadPlugins()
var babel = require('gulp-babel')
require('babel-register')({
presets:["es2015", "react", "stage-1"]
});
// This is a cheap way of getting 'test:browser' to run fully before 'test:api' kicks in.
gulp.task('test', ['test:browser'], function(){
return gulp.start('test:api')
});
gulp.task('test:api', function () {
global.env = 'test'
gulp.src(['test/unit-tests/server/**/*.spec.js'], {read: false})
.pipe(plugins.mocha({reporter: 'spec'}))
.once('error', function (error) {
console.log(error)
process.exit(1);
})
.once('end', function () {
process.exit(0);
})
});
gulp.task('default', ['test']);
Any help on why this is happening wouldd be much appreciated.
Node version 8 already has support for async/await so you do not need Babel to transform it; indeed, your root .babelrc includes this preset to exclude the regenerator that would transform async/await (and introduce a dependency on regeneratorRuntime):
["env", {"exclude": ["transform-regenerator"]}]
However, in your test file, the configuration does not specify this preset. Instead, it specifies the preset "es2015", which does include the unwanted transform-regenerator (as you can see at https://babeljs.io/docs/plugins/preset-es2015/). If you change this to match the presets in the root .babelrc, you'll get more consistent results.
Strangely i ran into this issue after i upgraded to Node v8.10.0 from v8.6.x . I had used babel-require like so in my test-setup.js
require('babel-register')();
and the testing tools are Mocha,chai,enzyme + JSDOM . I was getting the same issue when i was making a async call to a API, also while using generator functions via sagas. Adding babel-polyfill seemed to have solved the issue.
require('babel-register')();
require('babel-polyfill');
i guess even babel docs themselves advocate using polyfill for generators and such
Polyfill not included
You must include a polyfill separately when using features that require it, like generators.
Ran into the same issue when running mocha tests from within Visual Studio Code.
The solution was to add the necessary babel plugins in the Visual Studio Code settings.json :
"mocha.requires": [
"babel-register",
"babel-polyfill"
],
I've run into this error before myself when using async/await, mocha, nyc, and when attempting to run coverage. There's never an issue when leveraging mocha for running tests, just with mocha tests while leveraging nyc for running coverage.
11) Filesystem:removeDirectory
Filesystem.removeDirectory()
Should delete the directory "./tmp".:
ReferenceError: regeneratorRuntime is not defined
at Context.<anonymous> (build/tests/filesystem.js:153:67)
at processImmediate (internal/timers.js:461:21)
You can fix the issue a couple of different ways.
Method 1 - NPM's package.json:
...
"nyc": {
"require": [
"#babel/register",
"#babel/polyfill"
],
...
},
...
It really depends which polyfill package you're using. It's recommended to use the scoped (#babel) variant: #babel/pollyfill. However, if you're using babel-polyfill then ensure that's what you reference.
Method 2 - Direct Import
your-test-file.js (es6/7):
...
import '#babel/polyfill';
...
OR
your-test-file.js (CommonJS):
...
require("#babel/polyfill");
...
Don't assign it to a variable, just import or require the package. Again, using the package name for the variant you've sourced. It includes the polyfill and resolves the error.
HTH

Resources