jestjs / jest

Delightful JavaScript Testing.
https://jestjs.io
MIT License
44.2k stars 6.46k forks source link

Bug? babel-jest creating malformed transformations in preprocessor #1942

Closed avanderhoorn closed 7 years ago

avanderhoorn commented 8 years ago

I have a file within the code base that Jest is trying to execute tests in that was getting a weird Unexpected token . exception being thrown as the test was running. I tracked it down to one of the babelJest.process step in the preprocessor that I have registered. The following shows a sample of a preprocessor that exhibits the issue, what the input is and what the output is.

If I take the input and run it directly in the live previewer on the babel site, the results are fine. This leads me to wonder if its one of the plugins that jest/babel-jest register or something to do with istanbul maybe.

Preprocessor with JS that cases jest/babel-jest/babel to create malformed js:

const babelJest = require('babel-jest');

module.exports = {
    process(src, path) {
        var content = "import React from 'react'; \n import { connect } from 'react-redux'; \n export class UrlText extends React.Component { \n render() { \n return <div>test</div>; \n } \n } \n export function mapStateToProps(state, ownProps) { \n return {}; \n } \n export default connect(mapStateToProps)(UrlText);";
        var result = babelJest.process(content, path);

        console.log(result);

        return src;
    },
};

Raw content formated:

import React from 'react';
import { connect } from 'react-redux';

export class UrlText extends React.Component {
  render() {
    return <div>test</div>; 
  }
}

export function mapStateToProps(state, ownProps) {
  return {}; 
}

export default connect(mapStateToProps)(UrlText);

And this is the malformed output that jest/babel-jest/babel creates:

/* istanbul ignore next */'use strict';Object.defineProperty(exports, "__esModule", { value: true });exports.UrlText = undefined;var _createClass = function () {function defineProperties(target, props) {for (var i = 0; i < props.length; i++) {var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);}}return function (Constructor, protoProps, staticProps) {if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;};}();exports.

mapStateToProps = mapStateToProps;var /* istanbul ignore next */_react = require('react'); /* istanbul ignore next */var _react2 = _interopRequireDefault(_react);var /* istanbul ignore next */_reactRedux = require('react-redux'); /* istanbul ignore next */function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}function _classCallCheck(instance, Constructor) {if (!(instance instanceof Constructor)) {throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self, call) {if (!self) {throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call && (typeof call === "object" || typeof call === "function") ? call : self;}function _inherits(subClass, superClass) {if (typeof superClass !== "function" && superClass !== null) {throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;}var UrlText = exports.UrlText = function (_React$Component) {_inherits(UrlText, _React$Component);function UrlText() {_classCallCheck(this, UrlText);return _possibleConstructorReturn(this, (UrlText.__proto__ || Object.getPrototypeOf(UrlText)).apply(this, arguments));}_createClass(UrlText, [{ key: 'render', value: function render() {return (/* istanbul ignore next */_react2.default.createElement( /* istanbul ignore next */'div', /* istanbul ignore next */null, /* istanbul ignore next */'test'));} }]);return UrlText;}( /* istanbul ignore next */_react2.default.Component);function mapStateToProps(state, ownProps) {
  return {};
} /* istanbul ignore next */exports.default =
/* istanbul ignore next */(0, _reactRedux.connect)(mapStateToProps)(UrlText);

You can see that for some reason, babel is placing a number of line breaks just after the exports. which is causing the following exception:

    SyntaxError: Unexpected token .

      at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:284:10)
      at Object.<anonymous> (src/client/common/components/UrlText.tsx:16:419)
      at Object.<anonymous> (test/client/common/components/UrlText.spec.ts:1:170)

Here is the output from --debug:

jest version = 16.0.1
test framework = jasmine2
config = {
  "scriptPreprocessor": "/Users/avanderhoorn/Projects/Client/preprocessor.js",
  "moduleFileExtensions": [
    "ts",
    "tsx",
    "js",
    "jsx"
  ],
  "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js|jsx)$",
  "moduleDirectories": [
    "node_modules"
  ],
  "rootDir": "/Users/avanderhoorn/Projects/Client",
  "name": "-Users-avanderhoorn-Projects-Client",
  "setupFiles": [],
  "testRunner": "/Users/avanderhoorn/Projects/Client/node_modules/jest-jasmine2/build/index.js",
  "automock": false,
  "bail": false,
  "browser": false,
  "cacheDirectory": "/var/folders/jh/_qfb31ks75s36xc8_llzs4t40000gn/T/jest",
  "clearMocks": false,
  "coveragePathIgnorePatterns": [
    "/node_modules/"
  ],
  "coverageReporters": [
    "json",
    "text",
    "lcov",
    "clover"
  ],
  "globals": {},
  "haste": {
    "providesModuleNodeModules": []
  },
  "mocksPattern": "__mocks__",
  "moduleNameMapper": {},
  "modulePathIgnorePatterns": [],
  "noStackTrace": false,
  "notify": false,
  "preset": null,
  "preprocessorIgnorePatterns": [
    "/node_modules/"
  ],
  "resetModules": false,
  "testEnvironment": "jest-environment-jsdom",
  "testPathDirs": [
    "/Users/avanderhoorn/Projects/Client"
  ],
  "testPathIgnorePatterns": [
    "/node_modules/"
  ],
  "testURL": "about:blank",
  "timers": "real",
  "useStderr": false,
  "verbose": null,
  "watch": false,
  "cache": false,
  "watchman": true,
  "testcheckOptions": {
    "times": 100,
    "maxSize": 200
  }
}
quantizor commented 8 years ago

Potentially related to #1922.

@avanderhoorn can you test against jest-cli@15 babel-jest@15 and see if you have the same issue?

jcperez-ch commented 7 years ago

Seems like babel doesn't read the .babelrc file. so it doesn't include any of the plugins nor the presets defined there. Having a similar issue, now the problem seems to be a SyntaxError: Unexpected token import

({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Action from './Action';
                                                                                             ^^^^^^
    SyntaxError: Unexpected token import

      at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:284:10)

My .babelrc is on the root project and looks like:

{
  "presets": [
    ["es2015", { "modules": false }],
    "stage-2",
  ],
  "plugins": [
    ["external-helpers"]
  ]
}

I have jest-cli@16.0.2 and babel-jest@16.0.0 I am confident my issue is related to the one described in this issue.

cpojer commented 7 years ago

Try jest --no-cache one time. This should be fixed with #2023.

github-actions[bot] commented 3 years ago

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.