Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Existing jest tests are failing with upgrade to craco major version 7 #536

Open
mdv27 opened this issue Mar 29, 2024 · 0 comments
Open

Existing jest tests are failing with upgrade to craco major version 7 #536

mdv27 opened this issue Mar 29, 2024 · 0 comments
Labels
bug Something isn't working

Comments

@mdv27
Copy link

mdv27 commented Mar 29, 2024

What's happening
Existing Jest tests are failing with below error after upgrade to craco v7. Error disappears when -- coverage --coverageDirectory=coverage/jest option is removed from test script which leads to no coverage report.

Error:

 ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • 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/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /app/src/pages/Auth/MyComponent.tsx:577
            _store$auth => {
            ^^^^^^^^^^^

    SyntaxError: Unexpected identifier

    > 1 | import MyComponent from './MyComponent';
        | ^
      2 | import Login from './Login';
      3 | import Logout from './Logout';
      4 |

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (src/pages/Auth/index.ts:1:1)

What should happen
Test should pass as before upgrade

To reproduce
Run the test:frontend script

CRACO version
(ex. 7.1.0)

CRACO config

const path = require('path');
const electronEntries = require('./craco.entries.js');

let entries = [];

if (process.env.NODE_ENV === 'development') {
  entries = [...entries, ...electronEntries];
}

exports.entries = entries;

const defaultEntryName = 'main';

const appIndexes = ['js', 'tsx', 'ts', 'jsx'].map((ext) =>
  path.resolve(__dirname, `src/index.${ext}`)
);

const configureMultipleEntries = (webpackConfig, { env, paths }) => {
  console.log('-- DEFAULT CONFIG --');
  console.log(webpackConfig.output);
  const defaultHtmlPlugin = webpackConfig.plugins.find(
    (plugin) => plugin.constructor.name === 'HtmlWebpackPlugin'
  );
  defaultHtmlPlugin['options']['chunks'] = [defaultEntryName];
  webpackConfig.plugins = webpackConfig.plugins.filter(
    (plugin) => plugin.constructor.name !== 'ForkTsCheckerWebpackPlugin'
  );
  if (!Array.isArray(webpackConfig.entry)) {
    webpackConfig.entry = [webpackConfig.entry];
  }

  const necessaryEntry =
    webpackConfig.entry.length === 1
      ? []
      : webpackConfig.entry.filter((file) => !appIndexes.includes(file));
  const multipleEntry = {};
  multipleEntry[defaultEntryName] = webpackConfig.entry;

  exports.entries.forEach((entry) => {
    multipleEntry[entry.name] = necessaryEntry.concat(entry.entry);
    // Multiple Entry HTML Plugin
    webpackConfig.plugins.unshift(
      new defaultHtmlPlugin.constructor(
        Object.assign({}, defaultHtmlPlugin.userOptions, {
          filename: entry.outPath,
          template: entry.template,
          chunks: [entry.name],
          publicPath: '../',
        })
      )
    );
  });
  webpackConfig.entry = multipleEntry;

  // Multiple Entry Output File
  let names = webpackConfig.output.filename.split('/').reverse();

  if (names[0].indexOf('[name]') === -1) {
    names[0] = '[name].' + names[0];
    webpackConfig.output.filename = names.reverse().join('/');
  }

  webpackConfig.devServer = {
    ...webpackConfig.devServer,
    client: {
      overlay: {
        errors: false,
        warnings: false,
        runtimeErrors: false,
      },
    },
  };

  console.log('-- CRACO CONFIG --');
  console.log(webpackConfig.output);

  webpackConfig.plugins.forEach((plugin) => {
    if (plugin.constructor.name === 'HtmlWebpackPlugin') {
      console.log(plugin);
    }
  });

  return webpackConfig;
};

exports.webpack = {
  configure: configureMultipleEntries,
};

package.json

{
  "name": "my-proj",
  "jest": {
    "resetMocks": false,
    "coverageReporters": [
      "text",
      "cobertura"
    ],
    "coveragePathIgnorePatterns": [
      "/node_modules/",
      "myEnvironment.js",
      "/e2e/"
    ],
    "transformIgnorePatterns": [
      "node_modules/(?!(ag-grid-react|ag-grid-community)/)"
    ],
    "moduleNameMapper": {
      "\\.(css|less|scss)$": "identity-obj-proxy",
      "worker-loader!": "__mocks__/workerMock"
    }
  },
  "nyc": {
    "extends": "./nyc-config.js",
    "all": true,
    "exclude": [
      "src/e2e/*",
      "myEnvironment.js",
      "**/*.d.ts",
      "src/__tests__/*"
    ]
  },
  "dependencies": {
    "@microsoft/applicationinsights-react-js": "^3.3.5",
    "@microsoft/applicationinsights-web": "^2.8.5",
    "@szhsin/react-menu": "^1.10.0",
    "@tanstack/react-query": "^4.0.10",
    "@tanstack/react-query-devtools": "^4.7.1",
    "@tanstack/react-virtual": "^3.0.0-beta.17",
    "@tiptap/core": "^2.1.12",
    "@tiptap/extension-color": "^2.0.3",
    "@tiptap/extension-font-family": "^2.0.3",
    "@tiptap/extension-placeholder": "^2.0.3",
    "@tiptap/extension-text-align": "^2.0.3",
    "@tiptap/extension-text-style": "^2.0.3",
    "@tiptap/extension-underline": "^2.0.3",
    "@tiptap/pm": "^2.0.3",
    "@tiptap/react": "^2.0.3",
    "@tiptap/starter-kit": "^2.0.3",
    "@types/react-color": "^3.0.6",
    "@types/use-persisted-state": "^0.3.1",
    "acorn": "^8.11.3",
    "ag-grid-community": "^29.3.4",
    "ag-grid-react": "^29.3.4",
    "assert": "^2.1.0",
    "axios": "^0.21.4",
    "bootstrap": "^4.6.2",
    "btoa": "^1.2.1",
    "buffer": "^6.0.3",
    "cheerio": "^1.0.0-rc.12",
    "classnames": "^2.2.6",
    "clipboardy": "^2.3.0",
    "copy-image-clipboard": "^2.1.2",
    "cropperjs": "^1.5.12",
    "date-fns": "^2.25.0",
    "dexie": "^3.2.3",
    "dexie-encrypted": "^2.0.0",
    "dexie-react-hooks": "^1.1.3",
    "diff": "^5.0.0",
    "dockerode": "^3.3.5",
    "electron-reload": "^2.0.0-alpha.1",
    "electron-store": "^8.1.0",
    "file-saver": "^2.0.2",
    "html-to-image": "^1.11.11",
    "html2canvas": "^1.3.2",
    "hyperformula": "^2.4.0",
    "jquery": "^3.6.0",
    "json-diff": "^0.5.4",
    "jszip": "^3.10.1",
    "jwt-decode": "^3.1.2",
    "localforage": "^1.9.0",
    "lodash": "^4.17.21",
    "mobx": "^6.0.1",
    "mobx-keystone": "^0.47.0",
    "mobx-react-lite": "^3.0.0",
    "moment": "^2.29.4",
    "numeral": "^2.0.6",
    "pako": "^2.1.0",
    "papaparse": "^5.4.1",
    "query-string": "^6.13.7",
    "randomcolor": "^0.6.2",
    "react": "^18.2.0",
    "react-archer": "^4.2.3",
    "react-bootstrap": "^1.6.7",
    "react-bootstrap-icons": "^1.10.3",
    "react-circular-progressbar": "^2.1.0",
    "react-color": "^2.19.3",
    "react-date-range": "^1.4.0",
    "react-datepicker": "^4.15.0",
    "react-dnd": "^11.1.3",
    "react-dnd-html5-backend": "^11.1.3",
    "react-dom": "^18.2.0",
    "react-draggable": "^4.4.3",
    "react-dropzone": "^11.2.3",
    "react-error-boundary": "^4.0.11",
    "react-hotkeys": "^2.0.0",
    "react-hotkeys-hook": "^4.3.3",
    "react-icons": "^4.3.1",
    "react-infinite-scroll-component": "^6.0.0",
    "react-joyride": "^2.3.0",
    "react-loading-overlay": "^1.0.1",
    "react-markdown": "^8.0.5",
    "react-mentions": "^4.1.1",
    "react-moment": "^1.1.1",
    "react-outside-click-handler": "^1.3.0",
    "react-papaparse": "^3.8.0",
    "react-player": "^2.9.0",
    "react-rnd": "^10.3.7",
    "react-router-dom": "^5.3.4",
    "react-scripts": "^5.0.1",
    "react-scroll-sync": "^0.9.0",
    "react-select": "^5.7.0",
    "react-split": "^2.0.14",
    "react-to-print": "^2.14.7",
    "react-truncate": "^2.4.0",
    "react-use": "^15.3.4",
    "recharts": "^2.5.0",
    "reconnecting-websocket": "^4.4.0",
    "remark-breaks": "^3.0.2",
    "remark-gfm": "^3.0.1",
    "sass": "^1.45.1",
    "selenium-webdriver": "^4.0.0-alpha.8",
    "serialize-query-params": "^2.0.2",
    "stream": "0.0.2",
    "swagger-ui-react": "^3.52.5",
    "tls": "0.0.1",
    "tweetnacl": "^0.14.5",
    "use-persisted-state": "^0.3.3",
    "use-query-params": "^2.0.0-rc.1",
    "use-react-screenshot": "^3.0.0",
    "util": "^0.12.5",
    "uuid": "^8.3.2",
    "xlsx": "^0.18.5"
  },
  "main": "./main.js",
  "scripts": {
    "test": "CI=true craco test --testRunner='jest-circus/runner' --env='./src/myEnvironment.js' --verbose --forceExit",
    "test:frontend": "npm run test -- --coverage --coverageDirectory=coverage/jest --testPathPattern=src/__tests__/*",    
  },  
  "engines": {
    "node": "14.21.3",
    "npm": "6.14.18"
  },
  "devDependencies": {
    "@babel/plugin-proposal-private-property-in-object": "^7.21.11",
    "@craco/craco": "^7.1.0",
    "@testing-library/dom": "^9.2.0",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^14.2.2",
    "@testing-library/user-event": "^13.5.0",
    "@types/bootstrap": "^4.5.0",
    "@types/classnames": "^2.2.10",
    "@types/diff": "^4.0.2",
    "@types/file-saver": "^2.0.1",
    "@types/jest": "^27.4.1",
    "@types/jquery": "^3.5.14",
    "@types/json-diff": "^0.5.0",
    "@types/jszip": "^3.4.1",
    "@types/lodash": "4.14.164",
    "@types/node": "^16.11.26",
    "@types/node-sass": "^4.11.1",
    "@types/numeral": "^2.0.1",
    "@types/pako": "^2.0.3",
    "@types/papaparse": "^5.3.7",
    "@types/randomcolor": "^0.5.5",
    "@types/react": "^18.2.66",
    "@types/react-date-range": "^1.4.1",
    "@types/react-datepicker": "^4.11.2",
    "@types/react-dom": "^18.2.22",
    "@types/react-infinite-scroll-component": "^4.2.5",
    "@types/react-mentions": "^4.1.0",
    "@types/react-outside-click-handler": "^1.3.0",
    "@types/react-router-dom": "^5.3.3",
    "@types/react-scroll-sync": "^0.8.0",
    "@types/react-select": "^5.0.1",
    "@types/react-truncate": "^2.3.3",
    "@types/react-window": "^1.8.2",
    "@types/recharts": "^1.8.24",
    "@types/selenium-webdriver": "^4.0.11",
    "@types/swagger-ui-react": "^3.35.0",
    "@types/uuid": "^8.3.0",
    "babel-preset-react-app": "^10.0.1",
    "concurrently": "^7.6.0",
    "cross-env": "^7.0.3",
    "electron": "^23.3.13",
    "electron-builder": "^23.6.0",
    "eslint-config-airbnb": "^18.1.0",
    "eslint-config-prettier": "^8.7.0",
    "eslint-import-resolver-typescript": "^2.7.1",
    "eslint-plugin-prettier": "^4.2.1",
    "force-resolutions": "^1.0.11",
    "html-webpack-plugin": "^5.6.0",
    "jest-circus": "^27.5.1",
    "nyc": "^15.1.0",
    "prettier": "^2.8.4",
    "source-map-support": "^0.5.21",
    "ts-jest": "^28.0.8",
    "typescript": "^4.3.5",
    "worker-loader": "^3.0.8"
  },
  "resolutions": {
    "swagger-client": "3.18.5",
    "jsx-ast-utils": "3.0.0",
    "@types/react": "^18.2.66"
  }
}

myEnvironment.js

const ParentEnvironment = require('jest-environment-jsdom');

class myEnvironment extends ParentEnvironment {
  failedTest = false;

  async handleTestEvent(event, state) {
    if (event.name === 'hook_failure' || event.name === 'test_fn_failure') {
      this.failedTest = true;
    } else if (this.failedTest && event.name === 'test_start') {
      event.test.mode = 'skip';
    } else if (event.name === 'test_start' && event.test.mode !== 'skip') {
      // eslint-disable-next-line no-console
      console.log(`Starting '${event.test.name}'`);
    }

    if (super.handleTestEvent) {
      await super.handleTestEvent(event, state);
    }
  }

  getVmContext() {
    return super.getVmContext();
  }
}

module.exports = myEnvironment;

Additional information
Tried creating jest.config.js, does not help.

@mdv27 mdv27 added the bug Something isn't working label Mar 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant