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

transformIgnorePatterns not working when ignoring untranspiled package from another Github repo #11067

Closed
Freddie-Pike opened this issue Feb 8, 2021 · 9 comments

Comments

@Freddie-Pike
Copy link

🐛 Bug Report

I am currently running into an issue where a jest test is breaking because I'm importing a package in another repo I have created in my package.json which breaks the test that imports that package. Using transformIgnorePatterns to ignore this package should fix this issue, but it unfortunately does not.

To Reproduce

In the package.json of freddies_testing_playground, I link greeter, another repo I have created like so:

"greeter": "[email protected]:Freddie-Pike/greeter.git#semver:0.0.1"

"Greeter" is a repo that I have setup that uses the Greeter example in the TypeScript docs to show an example of importing a Github repo in a package.json. Here's what the Greeter class looks in the greeter repo:

// From the TypeScript docs: https://www.typescriptlang.org/docs/handbook/classes.html
class Greeter {
  greeting: string;
  constructor(message: string) {
    this.greeting = message;
  }
  greet() {
    return "Hello, " + this.greeting;
  }
}
export default Greeter;

Unfortunately, a jest test in freddies_testing_playground breaks because of the greeter repo. A react component(I wanna stress up front, that the react component isn't breaking, as I have tested the component in the actual browser) called GreeterUI imports the greeter class like so:

import React from "react";
import PropTypes from "prop-types";
import Greeter from "greeter";

function GreeterUI({ person }) {
  const greeter = new Greeter(person);
  return <div>{greeter.greet()}</div>;
}

GreeterUI.propTypes = {
  person: PropTypes.string,
};

export default GreeterUI;

The test uses react-testing-library, which I wanna stress is not the problem here, as I have another test in this repo that uses react-testing-library which works fine. Here's the code for the test that's breakiing:

import React from "react";
import { render, screen } from "@testing-library/react";
import GreeterUI from "../GreeterUI";

describe("GreeterUI", () => {
  it("renders greeting text.", () => {
    render(<GreeterUI person={"Fred"} />);
    const greeting = screen.queryByText(/hello, fred/i);
    expect(greeting).toBeInTheDocument();
  });
});

When running the test suite using npm run test, this stack trace occurs:

 FAIL  js/components/GreeterUI/__tests__/GreeterUI.test.jsx
  ● 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:
     • 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/freddiepike/github_action_jest/node_modules/greeter/dist/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export { default } from "./Greeter";
                                                                                             ^^^^^^
    SyntaxError: Unexpected token 'export'
      1 | import React from "react";
      2 | import PropTypes from "prop-types";
    > 3 | import Greeter from "greeter";
        | ^
      4 | 
      5 | function GreeterUI({ person }) {
      6 |   const greeter = new Greeter(person);
      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1266:14)
      at Object.<anonymous> (js/components/GreeterUI/GreeterUI.jsx:3:1)
Test Suites: 1 failed, 2 passed, 3 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        9.077 s
Ran all test suites.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] test: `jest --runInBand`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/freddiepike/.npm/_logs/2020-11-16T22_05_57_035Z-debug.log

Reading the stack trace, I have tried to set the transformIgnorePatterns in order for the greeter import so the import works. Here's the excerpt of what the transformIgnorePatterns does in my jest.config.js.

transformIgnorePatterns: ["<rootDir>/node_modules/(?!${greeter})"],

This still returns the same error, despite following the snippet from the jest docs on this that says:

Sometimes it happens (especially in React Native or TypeScript projects) that 3rd party modules are published as untranspiled. Since all files inside node_modules are not transformed by default, Jest will not understand the code in these modules, resulting in syntax errors. To overcome this, you may use transformIgnorePatterns to allow transpiling such modules. You'll find a good example of this use case in React Native Guide.

I've done a bit of research on this issue, and found that this is a common error and I have tried to apply several solutions I've found with no luck. So any help on this issue would be much appreciated!

Expected behavior

The GreeterUI component should be able to be imported in my test and not break when importing the Greeter package.

Link to repl or repo (highly encouraged)

https://github.com/Freddie-Pike/freddies_testing_playground -> The repo that uses the greeter package, broken test located in js/components/GreeterUI/tests/GreeterUI.test.jsx.
https://github.com/Freddie-Pike/greeter -> The repo that causes the test failure.
Greeter example in the TypeScript docs: https://www.typescriptlang.org/docs/handbook/classes.html

Github issues I found about this problem that unfortunately didn't help:

nrwl/nx#812
#6053

envinfo

freddiepike$ npx envinfo --preset jest
npx: installed 1 in 1.264s

  System:
    OS: macOS 10.15.7
    CPU: (4) x64 Intel(R) Core(TM) i5-7360U CPU @ 2.30GHz
  Binaries:
    Node: 13.11.0 - /usr/local/bin/node
    Yarn: 1.22.4 - /usr/local/bin/yarn
    npm: 6.14.8 - /usr/local/bin/npm
@Freddie-Pike
Copy link
Author

Hmm, this issue has the "Needs Repro" label on it yet it has repos that reproduce this issue. Can anyone with permissions to remove that label do so for me?

@leepowelldev
Copy link

should this:

transformIgnorePatterns: ["<rootDir>/node_modules/(?!${greeter})"],

be this?

transformIgnorePatterns: ["<rootDir>/node_modules/(?!(greeter)/)"],

@here-kulkarni
Copy link

did it help?

@julienw
Copy link

julienw commented Jan 3, 2023

Another gotcha where I just spent 2h is that the current version of Babel doesn't process files in node_modules if its configuration is defined in .babelrc. Renaming to babel.config.json works. More information and rationale there => https://babeljs.io/docs/en/config-files

@shubh-tharani
Copy link

I have jest configured in package.json

"jest": {
"resetMocks": false,
"transform": {
"^.+\.(js|jsx)$": "babel-jest"
},
"transformIgnorePatterns": [
"/node_modules/(?!(@Shopify|d3-scale))/"
],
"coverageReporters": [
[
"lcov",
{
"projectRoot": "../../"
}
]
]
},

And I have configured babel.config.js

module.exports = {
presets: [
[
"@babel/preset-env",
{
targets: {
node: "current",
},
},
],
"@babel/preset-react",
],
};

I am getting this error while running the tests -

node_modules/d3-scale/src/index.js:1
({"Object.":function(module,exports,require,__dirname,__filename,global,jest){export {
^^^^^^

SyntaxError: Unexpected token 'export'

  at Runtime.createScriptFromCode (../../node_modules/jest-runtime/build/index.js:1350:14)
  at Object.<anonymous> (../../node_modules/@shopify/polaris-viz-core/build/cjs/utilities/createGradient.js:5:15)

If i remove the import of package @shopify/polaris-viz, the tests run successfully.
can somebody help me with this?

@julienw
Copy link

julienw commented May 11, 2023

It looks like that your configuration uses @Shopify (capital letter S) while the package is in a directory @shopify (small letter s). Could that be your problem?

Copy link

This issue is stale because it has been open for 1 year with no activity. Remove stale label or comment or this will be closed in 30 days.

@github-actions github-actions bot added the Stale label May 10, 2024
Copy link

github-actions bot commented Jun 9, 2024

This issue was closed because it has been stalled for 30 days with no activity. Please open a new issue if the issue is still relevant, linking to this one.

@github-actions github-actions bot closed this as not planned Won't fix, can't repro, duplicate, stale Jun 9, 2024
Copy link

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.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Jul 10, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

6 participants