-1

I am making use of axios in my react app along with MUI for styling. I had no error while development but now when i started to write test for my react app using react testing library and jest i get axios module error as shown below . I went through many articles and it is most likely because of axios changed the module type from CommonJS to ECMAScript. I tried to modify this solution for Vue.js in react but i could not do it.

 FAIL  src/components/user/Contact.test.js
  ● 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:

    D:\Programs\VS Code\Web Development\lmsfrontend\node_modules\axios\index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import axios from './lib/axios.js';

          ^^^^^^

    SyntaxError: Cannot use import statement outside a module

    > 1 | import axios from "axios";
        | ^
      2 |
      3 | const API_URL = "https://librarymngsys.adaptable.app/api/user";   
      4 |

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (src/features/user/userService.js:1:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.254 s
Ran all test suites related to changed files.

Below is my test:

import { render, screen } from "@testing-library/react";
import Contact from "./Contact";
describe("Contact", () => {
  test("renders correctly", () => {
    render(<Contact />);
    const inputElem = screen.getByLabelText(/Name/)
    expect(inputElem).toBeInTheDocument();
  });
});

Below are the textfields in my component for which i am the writing tests: Note: i did not write test for second field because the first one itself is giving error

const Contact = () => {
    // code 
    return (
        <Box>
            <Box><Typography variant="h2" sx={{ textAlign: 'center' }}>Contact Us</Typography></Box>
            <Card sx={{ minHeight: '77vh', boxShadow: '1px 2px #3f48f2' }}>
                <Box sx={{ m: 1 }}>
                    <TextField
                        required
                        fullWidth
                        id="contact-name"
                        label="Name"
                        name="name"
                        value={values.name}
                        onChange={handleChange}
                        onBlur={handleBlur}
                        helperText={errors.name && touched.name ? errors.name : null}
                        error={errors.name && touched.name}
                    />
                </Box>
                <Box sx={{ m: 1 }}>
                    <TextField
                        required
                        fullWidth
                        id="contact-mail"
                        label="E-Mail ID"
                        name="mail"
                        value={values.mail}
                        onChange={handleChange}
                        onBlur={handleBlur}
                        helperText={errors.mail && touched.mail ? errors.mail : null}
                        error={errors.mail && touched.mail}
                    />
                </Box>
            </Card>
        </Box>
    )
}

export default Contact

I went through certain solutions but i am unable to rectify it. Thanks in advance.

Roshan Shetty
  • 267
  • 1
  • 13

4 Answers4

4

To fix this i updated my test command in my package.json to this : "test": "react-scripts test --transformIgnorePatterns 'node_modules/(?!axios)/'",. This error is because axios changed their module type from CommonJS TO ECMAScript in their v1.x.x and higher.

Roshan Shetty
  • 267
  • 1
  • 13
2

For those who still getting this error when running tests in Jest in 2023. It mostly happens when you are using CRA to create a React project. CRA will take the configurations inside the package.json instead of consuming your configurations in the jest.config.js file. Here is the reference: https://create-react-app.dev/docs/running-tests/#configuration

The way I fixed this error is ejecting the React app by using craco. And here is my configurations to make it work.

jest: {
    configure: {
      moduleNameMapper: { '^axios$': 'axios/dist/node/axios.cjs' },
    },
  },

My jest and axios version:

  • axios@1.4.0
  • jest@27.5.1
Thomas Vu
  • 105
  • 1
  • 7
1

"axios": "^0.27.2" works. uninstall your axios: npm uninstall axios and install: npm install --save axios@0.27.2

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 21 '23 at 16:21
-1

In my case:

axios 1.0 and higher are not compatible with the jest tests

Change the dependency in the package.json to:

"axios": "^0.20.0"

After doing this I had issues with my code crashing so I had to:

Remove the node_modules directory: rm -rf node_modules

Clear the npm cache: npm cache clean --force

Reinstall the dependencies: npm install

It worked for me after searching high and low through the forums and not finding a solution. Thankfully someone more familiar with the project was able to step in. Hopefully it works for you.

Ivan Chew
  • 9
  • 4