Trying to run the example of Jest testing React code (from https://github.com/facebook/jest/tree/master/examples/react ), I get the following error:
> # test /home/aizquier/jest/examples/react
> jest
Using Jest CLI v0.7.1
FAIL __tests__/CheckboxWithLabel-test.js
● Runtime Error
SyntaxError: /home/aizquier/jest/examples/react/__tests__/CheckboxWithLabel-test.js: Unexpected token (15:6)
npm ERR! Test failed. See above for more details.
The tests fails at line 15 of file CheckboxWithLabel-test.js:
jest.dontMock('../CheckboxWithLabel');
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
const CheckboxWithLabel = require('../CheckboxWithLabel');
describe('CheckboxWithLabel', function() {
it('changes the text after click', function() {
// Render a checkbox with label in the document
var checkbox = TestUtils.renderIntoDocument(
<CheckboxWithLabel labelOn="On" labelOff="Off" />
);
var checkboxNode = ReactDOM.findDOMNode(checkbox);
// Verify that it's Off by default
expect(checkboxNode.textContent).toEqual('Off');
// Simulate a click and verify that it is now On
TestUtils.Simulate.change(TestUtils.findRenderedDOMComponentWithTag(checkbox, 'input'));
expect(checkboxNode.textContent).toEqual('On');
});
});
apparently the preprocessor to handle .jsx is not working. The package.json is as follows:
{
"dependencies": {
"react": "~0.14.0",
"react-dom": "~0.14.0"
},
"devDependencies": {
"react-addons-test-utils": "~0.14.0",
"babel-jest": "*",
"jest-cli": "*"
},
"scripts": {
"test": "jest"
},
"jest": {
"scriptPreprocessor": "./node_modules/babel-jest",
"unmockedModulePathPatterns": [
"./node_modules/react",
"./node_modules/react-dom",
"./node_modules/react-addons-test-utils",
"./node_modules/fbjs"
]
}
}
My node is v4.2.2 and npm is 3.3.12.
Any ideas??
I was running into the same problem. It looks like this is an issue caused by the recent release of Babel 6. It's being tracked here, and hopefully a fix is added soon!
In the meantime, you can go back to an earlier version of babel-jest in your package.json. For example, try ^5.3.0.
If you are using Babel 6 there are no default transformations so you'll need to add some presets. Not sure if you can do this in 'package.json' but I added the '.babelrc' file with the 'react' and 'es2015' presets and that sorted it. See http://babeljs.io/docs/plugins/preset-react/
Related
For some reason, my jest configuration doesn't work with the latest version of d3-path#3.0.1. It worked fine with version 2.0.0. I guess it has something to do with d3-path switching to ESM, but I was already using ES6 in my own code, so I don't get why it suddenly doesn't work anymore. I have the following packages installed:
"dependencies": {
"d3-path": "^3.0.1"
},
"devDependencies": {
"#babel/core": "^7.15.8",
"#babel/preset-env": "^7.15.8",
"babel-jest": "^27.3.1",
"jest": "^27.3.1"
}
My babel.config.js:
module.exports = {
presets: [['#babel/preset-env', {targets: {node: 'current'}}]],
};
My index.js:
import { path } from 'd3-path'
export default () => path()
The test file:
import fn from '../src/index.js'
describe('test', () => {
it('works', () => {
fn()
expect(2 + 2).toBe(4)
})
})
The error message:
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export {default as path} from "./path.js";
^^^^^^
SyntaxError: Unexpected token 'export'
> 1 | import { path } from 'd3-path'
To reproduce:
git clone https://github.com/luucvanderzee/jest-problem.git
cd jest-problem
npm i
npm run test
// The test runs without failure- this is because we're currently still using d3-path#2.0.0
npm uninstall d3-path && npm install d3-path // (upgrade to d3-path#3.0.1)
npm run test
// Now the test fails.
How should I configure jest and/or babel to solve this issue?
EDIT:
I already tried the following (from this page of the jest docs):
Creating a jest.config.js file with the following:
module.exports = {
transform: {}
}
Changing my "test" command from "jest" to "node --experimental-vm-modules node_modules/jest/bin/jest.js"
This gives me another error:
/home/luuc/Projects/javascript/jest-problem/test/test.test.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import fn from '../src/index.js'
^^^^^^
SyntaxError: Cannot use import statement outside a module
I also don't get what is meant by
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
Isn't the problem that the module is not transformed? Would adding an ignore pattern not just lead to the module not getting transformed?
Problem
The error happens because jest does not send the content of node_modules to be transformed by babel by default.
The following output line of npm run test indicates one way to solve the problem:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
Solution
The configuration of jest should be updated in order to instruct it to transform the ESM code present in d3-path dependency.
To do so, add the following to a jest.config.js file in the root directory of the project:
module.exports = {
transformIgnorePatterns: ['node_modules/(?!(d3-path)/)']
}
npm run test runs fine after that.
The transformIgnorePatterns option is documented here.
Edit - including more modules
In order to include all modules starting with d3, the following syntax may be used:
transformIgnorePatterns: ['/node_modules/(?!(d3.*)/)']
TLDR;
transformIgnorePatterns: [
"/node_modules/(?!d3|d3-array|d3-axis|d3-brush|d3-chord|d3-color|d3-contour|d3-delaunay|d3-dispatch|d3-drag|d3-dsv|d3-ease|d3-fetch|d3-force|d3-format|d3-geo|d3-hierarchy|d3-interpolate|d3-path|d3-polygon|d3-quadtree|d3-random|d3-scale|d3-scale-chromatic|d3-selection|d3-shape|d3-time|d3-time-format|d3-timer|d3-transition|d3-zoom}|internmap|d3-delaunay|delaunator|robust-predicates)"
]
For the ones reaching this page after updating recharts dependency, here I found the solution, provided by them.
I am trying to start using react-testing-library on my project.
Problem is, I can't setup everything properly.
Steps I made:
I installed #testing-library/react and jest-dom as documentation suggests.
I setup jest.config.js:
module.exports = {
setupFilesAfterEnv: [
'#testing-library/react/cleanup-after-each',
],
};
I wrote basic test:
import React from 'react';
import App from '../App';
import {render } from "#testing-library/react";
it('renders without crashing', () => {
const {asFragment} = render(<App/>);
expect(asFragment).toMatchSnapshot();
});
Error I get:
4 |
5 | it('renders without crashing', () => {
> 6 | const {asFragment} = render(<App/>);
| ^
7 | expect(asFragment).toMatchSnapshot();
8 | });
9 |
My packages versions from package.json file:
"#testing-library/react": "^8.0.4",
"jest-dom": "^3.5.0",
"jest": "^24.8.0",
"react": "^16.6.3",
"react-dom": "^16.6.3",
I've tried several things like cleanuping locally not from jest.config.js file to make it work, but nothing seems to work.
Edit: Project was created with CRA. Even though, I tried to configure babel and babel-jest myself as suggested but didn't work.
I can't tell what was the problem here to be honest. I only know it happen when I was switching from enzyme to react-testing-library.
Note: reverting to enzyme didn't work.
However, I can tell what worked. It was CRA-based project, which means I had all babel, webpack and jest configuration hidden from me. I decided to run npm eject only to fix configuration. Yet, after running this command tests started working again.
I've been bashing my head against this brick wall for a day now so it's time to turn to SO for help I think! I'm trying to update a project off babel v5, I'm starting off with this in package.json:
"devDependencies": {
"babel": "^5.8.21",
"test": "mocha --require babel/register",
I've tried to upgrade to babel both v6 and v7 with no success either time. In both cases I end up with TypeError: _application.ApplicationClient is not a constructor when I attempt to run tests that worked fine with v5:
import { ApplicationClient } from '../src/wiotp/sdk/application';
...
let client = new ApplicationClient();
Using v6 as an example, I end up with the following in package.json:
"devDependencies": {
"babel-cli": "^6.0.0",
"babel-core": "^6.0.0",
"babel-preset-env": "^1.7.0",
"mocha": "6.1.4",
"test": "mocha --require babel-core/register --timeout 5000",
and created a .babelrc file (none existed previously):
{
"presets": ["env"]
}
I've read a dozen or more articles trying to understand what is going on here, I've done and undone numerous suggested "fixes" based on Google searches for similar problems, but I'm starting from zero and finding it incredibly hard to get simple plain-English explanation of what the actual problem is for a start, and how babel is supposed to be configured here to resolve it. I'm guessing something that happened by default in v5 needs to be configured somehow in .babelrc now, but /shrugs/ no idea where to go from here now.
babel5 to babel6 branch compare
babel5 to babel7 branch compare
Any pointers for someone struggling to wrap his head around babel, let alone the differences between v5, 6, & 7?
Edit:
src/wiotp/sdk/application/index.js has this:
import { default as ApplicationClient } from './ApplicationClient';
export default {
ApplicationClient
}
Where src/wiotp/sdk/application/ApplicationClient.js has a single class exported (I'm just trying to create an instance of that class in the test code):
export default class ApplicationClient extends BaseClient {
constructor(config) {
src/wiotp/sdk/application/index.js has this:
import { default as ApplicationClient } from './ApplicationClient';
export default {
ApplicationClient
}
This is horrible, and causing your problem. That module does default-export an object literal, instead of just using named exports. It might be a bug and they meant to write either
import { default as ApplicationClient } from './ApplicationClient';
export { ApplicationClient }
or
export { default as ApplicationClient } from './ApplicationClient';
It would recommend to report an issue and provide a patch.
If this is not considered a bug but was done on purpose, you will need to change your code to
import application from '../src/wiotp/sdk/application';
…
let client = new application.ApplicationClient();
// ^^^^^^^^^^^^
or just import it directly from the original module:
import ApplicationClient from '../src/wiotp/sdk/application/ApplicationClient.js';
// ^^^^^^^^^^^^^^^^^^^^^
…
let client = new ApplicationClient();
I had an issue with importing the LitElement module into a Meteor project:
I'm starting a new test project with Meteor 1.7+ and am using LitElement for a few components.
I installed Meteor like so:
meteor create meteor-lithtml --release 1.7.1-beta.29 --bare
I installed like so:
meteor npm install --save #polymer/lit-element
My node_modules directory looks like so:
My package.json file:
{
"name": "myapp",
"private": true,
"scripts": {
"start": "meteor run"
},
"dependencies": {
"#babel/runtime": "^7.0.0-beta.56",
"#polymer/lit-element": "^0.5.2",
"#vaadin/router": "^1.0.0",
"meteor-node-stubs": "^0.4.1",
"redux": "^4.0.0"
},
"meteor": {
"mainModule": {
"client": "client/index.js",
"server": "server/index.js"
}
}
}
The typical way I see lit-element imported is not working...
Just adding an index.js file and importing the lit-element module generates errors. If I remove the import from the index.js file, the errors go away.
\\ client\index.js
import { LitElement, html } from '#polymer/lit-element';
The very first error:
Uncaught SyntaxError: Unexpected token {
modules.js?hash=182125a3fa97eaa24f6d313584ca593c3aed2103:984
Points to this location:
Expanding node_modules to look into this file:
Why am I getting the unexpected { token?
NOTE: I'm asking this question here just in case a Meteor user stumbles by with the same issue and needs help.
Just in case we have any more Meteor users stop by with an issue like this, here are the references to the explanation & solution:
explanation: https://forums.meteor.com/t/litelement-import-litelement-html/45042/8?u=aadams
solution: https://github.com/aadamsx/meteor-lithtml/pull/1
I am trying to set up a basic modular program, however I seem to be running into issues with importing modules. I attempt to import my custom module, I get the following error:
(function (exports, require, module, __filename, __dirname) { import testStep from 'testStep';
^^^^^^
SyntaxError: Unexpected token import
The code that is causing the issue:
testcase.js
import testStep from 'testStep';
testStep.hello();
testStep.js
var testStep = {
hello: hello,
};
var hello = () => {
console.log('hello world');
};
export default {testStep};
package.json
{
"name": "rebuild-poc",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-polyfill": "^6.23.0",
"babel-preset-env": "^1.6.0"
},
"dependencies": {}
}
.babelrc
{
"presets": [
"env"
]
}
I have already tried several other fixes, such as setting testStep as a class, as well as using require('./testStep.js'), however neither of those seem to have worked.
Do I have something set up incorrectly with babel or in one of my files?
***Edit: I am running testCase.js with node testCase.js.
Please install babel-cli and call your file with: ./node_modules/.bin/babel-node testcase.js
It will fail. Now we have to fix your code.
testStep.js should look like:
var hello = () => {
console.log('hello world');
};
var testStep = {
hello: hello,
};
export default testStep;
Then, it will work. ;)
This first introduction on https://babeljs.io/ is, that you should install babel-cli and babel-preset-env. ;)
You can also write your testStep.js like this:
var testStep = {
hello: hello,
};
function hello () {
console.log('hello world');
};
export default testStep;
This keeps the hoisting in mind. Like Jacob said in his first point.
From the babel 6 Release notes:
Plugin Presets
$ npm install --save-dev babel-preset-env
save it .babelrc file
{
presets: ["env"]
}
Note:
https://babeljs.io/docs/en/babel-preset-env#docsNav
You need to define hello with function, using var, you will not have function hoisting, so when declaring testStep, hello is undefined.
If you want to use es module, you can use babel-register or babel-node.
In your code, node can not handle es module.
Babel-register
With bebel-register, all your module will be handled by babel when they are imported.
First,yarn add babel-register babel-cli --dev or npm install babel-register
babel-cli -dev
Then create an entry file:
// entry.js
require('babel-register')
require('testcase')
In your testcase, you can use es module now.
Edit you package.json:
"scripts": {
"test": "node entry.js"
},
you can run yarn test or npm run test in terminal.
You don't need babel-polyfill, that is for browsers, not for node.