Have Babel transpile configuration files into CommonJS format

I'm having trouble getting my Nuxt app to work with Jest for testing. I have a setupFilesAfterEnv property set with a setupTests.ts file that imports a translation file. The translations file uses ES6 import/export module syntax, but it seems like my current configuration isn't transpiling it properly.

Shouldn't babel-jest be transpiling the .js files due to the transform property?

setupTests.ts

import { config } from '@vue/test-utils';
import flat from 'flat';
import '@testing-library/jest-dom/extend-expect';
import 'jest-axe/extend-expect';
import frenchTranslations from '~/config/translations/fr-FR';
...

babel.config.json

{
  "presets": ["@babel/preset-env", { "targets": { "node": "current" } }]
}

jest.config.js

module.exports = {
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/$1',
    '^~/(.*)$': '<rootDir>/$1',
    '^vue$': 'vue/dist/vue.common.js',
  },
  moduleFileExtensions: ['ts', 'js', 'vue', 'json'],
  resolver: '<rootDir>/test/integration/resolver.js',
  transform: {
    '^.+\\.ts$': 'ts-jest',
    '^.+\\.js$': 'babel-jest',
    '^.+\\.vue$': '@vue/vue2-jest',
  },
  collectCoverage: true,
  collectCoverageFrom: [
    '<rootDir>/components/**/*.vue',
    '<rootDir>/pages/**/*.vue',
  ],
  testEnvironment: 'jsdom',
  passWithNoTests: true,
  setupFilesAfterEnv: ['<rootDir>/test/integration/setupTests.ts'],
};

/config/translations/fr-FR.js

export default {
 ...
}

Jest output

FAIL  test/integration/components/ui/RegistrationForm.test.ts
  ● 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:

    /my-project/config/translations/fr-FR.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export default {
                                                                                      ^^^^^^

    SyntaxError: Unexpected token 'export'

      1 | import { config } from '@vue/test-utils';
      2 | import flat from 'flat';
      3 | import '@testing-library/jest-dom/extend-expect';
      4 | import 'jest-axe/extend-expect';
    > 5 | import frenchTranslations from '~/config/translations/fr-FR';

      at Runtime.createScriptFromCode (node_modules/.pnpm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f757a6c6b326d6a716b76727a5f2d27312e313a">[email protected]</a>/node_modules/jest-runtime/build/index.js:1796:14)
      at Object.<anonymous> (test/integration/setupTests.ts:5:1)
      at TestScheduler.scheduleTests (node_modules/.pnpm/@<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94fef1e7e0bff7fbe6f1d4a6acbaa5baafaa">[email protected]</a>/node_modules/@jest/core/build/TestScheduler.js:317:13)

----------------------|---------|----------|---------|---------|-------------------
File                  | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------------------|---------|----------|---------|---------|-------------------
All files             |       0 |        0 |       0 |       0 |
 RegistrationForm.vue |       0 |        0 |       0 |       0 | 1-113
----------------------
Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.35 s
Ran all test suites related to changed files.

Answer №1

Consider updating your setupFilesAfterEnv to

setupFilesAfterEnv: ['@testing-library/jest-dom/extend-expect'],
and installing any necessary dependencies.

You might also want to modify your babel.config.js file like this:

// Conversion of modules to commonjs format for Jest compatibility.
const isTest = String(process.env.NODE_ENV) === 'test'
const isProd = String(process.env.NODE_ENV) === 'production'

module.exports = {
    // Transforming TSX and other react-related plugins
    presets: [
        // Smart transpilation based on target environments
        ['@babel/preset-env', { modules: isTest ? 'commonjs' : false }],
        // TypeScript support for Babel
        '@babel/preset-typescript',
    ],
}

Note: If your codebase is not in typescript, you can ignore the typescript preset.

Note2: Changing from babel.config.json to babel.config.js may offer improvements as well.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Trouble in Transmitting: Node.js Fails to

As a beginner in programming, I am currently following a tutorial to enhance my skills. I've encountered a roadblock and I can't seem to successfully post new entries using the code. I'm struggling to identify what I might be missing here. ...

Guide to choosing an option in a select dropdown using Vue?

<span class="input-group-btn" style="min-width: 100px"> <select class="form-control" v-model="field.related_field"> <option value="null"></option> <option v-for="f in fields" v-bind:val ...

Issue with the svg animation not properly "executing"

Hello everyone! This is my debut post, and usually I can find solutions by browsing the community. However, this time I am in need of some assistance. I have crafted an "SVG" file that includes animations depicting the different cycles of a day over a 24-h ...

ValueError: Unable to perform slicing operation on this data

When attempting a query in nodejs, I encounter this error: [2017-08-19 19:06:55.946] [ERROR] error - TypeError: val.slice is not a function at escapeString (/var/www/Bot/node_modules/sqlstring/lib/SqlString.js:183:23) at Object.escape (/var/www/Bo ...

Transforming Google Maps from using jQuery to AngularJS

If I have a Jquery google map with find address and routing system, my goal is to convert it to an angular google map with more options. The current Jquery google map code looks like this: var directionsDisplay = new google.maps.DirectionsRenderer({ d ...

Verify whether the value is considered false, true, or null

When dealing with variables in JavaScript, I often need to determine if a variable is false, true, or null. If the variable is null or undefined, I want to assign an array to it by default. While this syntax works well in other languages, in JS assigning a ...

What is the best way to create ng-options that only display unique values?

I am trying to modify my ng-options element so that it only displays unique values. Currently, it looks like this: https://i.sstatic.net/5CtSk.png However, I want it to display one value at a time. For example: <select class="form-control" ng-model=" ...

The onload function in jQuery is not functioning properly when the page is refreshed

I'm just starting out with jquery and I have a simple project in mind. The idea is to have two pictures stacked on top of each other, but I want the page to start showing the second picture first (at a specific scroll point). Then as the user scrolls ...

The issue of Angular curly braces malfunctioning in some simple code examples reversed my

<head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"> </script> </head> <body style="padding: 20px 20pc;"> <div ng-app="app"> ...

Execute a PHP script to retrieve data from a database based on the content of a text element

I'm currently working on a web-based system and I'm wondering if it's possible to retrieve a Name based on the number entered in a text box. Here is what I have attempted so far, but I know it's not functioning properly. Is there an alt ...

Is there a way to check if VueJs /Vuetify is currently in the middle of an animation?

When working with Angular and Jquery, it's easy to determine if something on the page is currently animating. By using the css selector ".ng-animating", you can check if any elements have the animating class applied to them. We rely on this functiona ...

Is it possible to load multiple angular applications within a master angular shell application?

I am searching for a method to integrate multiple Angular applications into a single shell Angular application. The concept involves having different teams develop separate Angular apps that can be loaded within a main shell app visible to end users. Thi ...

"Effortlessly transform a JSON string into a JSON Object with JavaScript - here's how

When I serialize my object using the ASP.net JavaScriptSerializer class and return it to the client side, how can I deserialize the string in JavaScript? ...

Showing time on a JSON document using JavaScript Timeline

Currently, I am in the process of creating a widget using a timeline JS template. The main challenge lies in receiving events in JSON format, which is essential for the functionality of the widget. At this stage, my focus is on being able to fetch events f ...

Unable to retrieve the value stored in the global variable

I recently updated my code to use global variables for two select elements in order to simplify things. Previously, I had separate variables for values and innerHTML which felt redundant. Now, with global variables like user and group initialized at docum ...

Is there a substitute for AngularJS $watch in Aurelia?

I'm in the process of transitioning my existing Angular.js project to Aurelia.js. Here is an example of what I am trying to accomplish: report.js export class Report { list = []; //TODO listChanged(newList, oldList){ ...

`How can I define dependencies and build an npm package?`

I have authored several npm modules, all of which are designed to enhance existing libraries such as three.js or react. While the packages appear to be downloaded, I have not received any feedback confirming whether they have been implemented correctly. ...

Is this conditional statement accurate?

Could this be a legitimate condition? Why isn't it functioning as expected in PHP? var myString = 'hello'; if(myString == ('hello' || 'hi' || 'bonjour' || 'hallo')){ alert('Welcome'); } ...

Share edited collection with Observer

The challenge Imagine creating an Angular service that needs to expose an Observable<number[]> to consumers: numbers: Observable<number[]>; Our requirements are: Receive the latest value upon subscription Receive the entire array every tim ...

Struggling with expanding a Javascript object? Let us assist you!

Imagine having a JavaScript object... app.widget = {} (function (W) { W.superFunction = function() { console.log("Hey!"); } ...other functions... })(app.widget) Now, let's create a clone of this object... app.specialWidget ...