Encountering an unexpected token while trying to use createUserWithEmailAndPassword in firebase/auth with Next.js and TypeScript left Jest puzzled

I have been working on integrating Firebase authentication into my Next.js project (using TypeScript), but it appears that there are configuration issues with Firebase causing my Jest tests to fail.

Here are the key configuration files:

jest.config.js :

const nextJest = require("next/jest");

const createJestConfig = nextJest({
  // Specify the path to your Next.js app to load next.config.js and .env files in the test environment
  dir: "./",
});

// Add any custom configurations for Jest
const customJestConfig = {
  setupFilesAfterEnv: ["<rootDir>/jest.setup.js"],
  moduleNameMapper: {
    // Manage module aliases
    "^@/components/(.*)$": "<rootDir>/components/$1",
    "^@/pages/(.*)$": "<rootDir>/pages/$1",
  },
  testEnvironment: "jest-environment-jsdom",
};

module.exports = createJestConfig(customJestConfig);

tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "firebase.js"],
  "exclude": ["node_modules"]
}

package.json:

{
  "name": "video-annotator",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "test": "jest --watch",
    "test:ci": "jest --ci"
  },
  ...
}

In my troubleshooting, I encountered an error related to:

const userInfo = await createUserWithEmailAndPassword(
          auth,
          email,
          password
        );

in the file pages/create-account/index.tsx around line 94.

The error message indicates an unexpected token issue when Jest encounters the code snippet above.

Further details revealed a SyntaxError related to 'export' within a Firebase file:

.../video-annotator/node_modules/firebase/auth/dist/esm/index.esm.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export * from '@firebase/auth';
                                                                                  ^^^^^^

SyntaxError: Unexpected token 'export'

...

I have tried various solutions, including modifying jest.config.js and setting up ts-jest, but the issue persists. Any guidance on next steps would be greatly appreciated.

Should I consider switching to Babel instead of ts-jest given the challenges faced?

You can find my repository with the problematic branch here. To replicate the error, clone the repo, switch to the create-account branch, install dependencies with `npm install`, and run `npm test`. Don't forget to create a './key.ts' file as indicated in the README.

Thank you in advance for any assistance!

Answer №1

I haven't had much experience with NexTJS, so please forgive me if I overlook anything.

With the help of this answer, I managed to get the tests running by simply adding the following code snippet:

module.exports = async () => ({
  ...(await createJestConfig(customJestConfig)()),
  transformIgnorePatterns: [
    '/node_modules/(?!(firebase|@firebase)/)',
  ]
});

Here is my complete jest.config.js file:

const nextJest = require("next/jest");

const createJestConfig = nextJest({
  dir: "./",
});

const customJestConfig = {
  setupFilesAfterEnv: ["<rootDir>/jest.setup.js"],
  moduleNameMapper: {
    "^@/components/(.*)$": "<rootDir>/components/$1",
    "^@/pages/(.*)$": "<rootDir>/pages/$1",
  },
  testEnvironment: "jest-environment-jsdom",
  
};

module.exports = async () => ({
  ...(await createJestConfig(customJestConfig)()),
  transformIgnorePatterns: [
    '/node_modules/(?!(firebase|@firebase)/)',
  ]
})

All tests passed successfully! :)

Test Suites: 2 passed, 2 total
Tests: 13 passed, 13 total
Snapshots: 0 total
Time: 6.104 s
Ran all test suites.

Interestingly, the examples in their documentation suggest that we can include the same pattern in the customJestConfig object.


Side note: Remember to revoke any secrets related to your firebase app and remove them from your repository.

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

Why does the req.cookies object contain cookies when using Supabase in combination with Next.js API routes?

Recently, I've been experimenting with using this helpful Supabase guide to implement authentication in Next.js. However, I'm encountering an issue where the server client function is not functioning as expected. Specifically, when trying to exec ...

Creating dynamic and engaging videos using Angular with the ability to make multiple requests

I am facing an issue while working with videos in Angular. I am fetching the video URLs from an API to embed them in my application using the sanitazer.bypassSecurityTrustResourceUrl function provided by Angular. The videos are being displayed correctly wi ...

Encountering a Difficulty while attempting to Distinguish in Angular

I am currently working on a form where I need to dynamically add controls using reactiveForms. One specific task involves populating a dropdown menu. To achieve this, I am utilizing formArray as the fields are dynamic. Data: { "ruleName": "", "ruleD ...

Configuration of injected services in IONIC 2

I am curious about how the services from injected work in IONIC 2. Specifically, my question is regarding the number of instances that exist when one service is used in two or more controllers. Previously, I asked a colleague who mentioned that IONIC 2 op ...

Exploring for JSON keys to find corresponding objects in an array and adding them to the table

I'm currently working on a project where I need to extract specific objects from a JSON based on an array and then display this data in a table. Here's how my situation looks: playerIDs: number[] = [ 1000, 1002, 1004 ] The JSON data that I am t ...

Vue.js seems to be leading me down a long and steady path of progress at a snail

I've exhausted all efforts to resolve the file paths for Home and App. I even turned to AI to help me out, but still no luck. Code snippet from main.js in the src folder: import Home from '@views/Home.vue'; // Using alias import App from ...

"Utilizing dynamic slugs in NextJS paths for enhanced routing

Is there a way to achieve the following scenario in NextJS? /route1 /translatedRoute1 /route2 /translatedRoute2 Given this folder structure pages/ [route1]/ index.js [route2]/ index.js An issue arises because [route1] and [route2] will both m ...

What is the best way to display a Chart using data pulled from redux?

I am struggling to display a chart based on the data retrieved from the Redux cart. Although I have successfully fetched the data attributes from the Redux store into an array, the chart does not appear as expected. Below is the code snippet from ChartPro ...

If the input is unmounted in react-hook-form, the values from the first form may disappear

My form is divided into two parts: the first part collects firstName, lastName, and profilePhoto, while the second part collects email, password, confirmPassword, etc. However, when the user fills out the first part of the form and clicks "next", the val ...

Tips for steering clear of getting caught in the initial focus trap

I have implemented Focus-trap (https://www.npmjs.com/package/focus-trap) in my modal to enhance keyboard accessibility. Here is a snippet of my code: <FocusTrap focusTrapOptions={{onDeactivate: onClose}} > <div> ... </div> <Focu ...

invoking a method within an express route to retrieve and utilize middleware functions

For my project, I am working on a custom function to handle API request validation. Here is how it looks: export function validateBody(schema: string): (req: ExpressRequest, res: ExpressResponse, next: ExpressNextFunction) => void { return function ...

Encountering a NextJS pre-render issue while generating the sitemap.xml

While developing my markdown-based blog, everything functioned smoothly in the developer environment. However, when I attempted to build the project using the command npm run build, I encountered an error related to pre-rendering failure. Error occurred pr ...

Tips for disabling Hot Module Reloading in NextJS

In my project built with ReactJS and NextJS, users can upload their pictures, manipulate faces, and animate them. However, we are facing an issue where the page automatically reloads due to HMR (Hot Module Replacement), causing all user data to be lost. ...

"Learn the step-by-step process of integrating Vendure (headless commerce) with Strapi CMS on Heroku for seamless deployment

Seeking guidance for deploying a webapp on Heroku with a unique tech stack: Frontend: NextJS (deployed on Vercel) CMS: Strapi (deployed on Heroku) Interested in adding a webshop using the Vercel/commerce example (https://github.com/vercel/commerce) and V ...

Loading large amounts of data efficiently with Angular and Firebase

Currently, I am utilizing AngularJS in conjunction with Firebase. Objective: My aim is to showcase all the information stored within my Firebase database (which consists of a fixed number of approximately 1600 items). Challenge: The issue at hand is that ...

Why is it that when the form is submitted, the value becomes unclear?

This is a form with HTML and TypeScript code that I am working on. <form> <div class="form-group"> <input class="form-control" ([ngModel])="login" placeholder="Login" required> </div> <div class="form-group"> &l ...

twice the custom nextjs responsive detection hook is being called

A custom hook has been developed that detects device on reload and resize events. import { useState, useEffect, useRef, useCallback } from "react"; export const DEVICE_SIZES_VALUE = { MOBILE: 576, TABLET: 768, DESKTOP: 992, LARGE_DESKTOP ...

Check if a value is present in the array with *ngIf

I'm curious about how to use the ngIf directive in a specific scenario. In my Angular application, I have dynamically generated angular material toggles, each with a unique id. I'm familiar with using ngIf to conditionally display elements on the ...

Issue with rendering HTML tags when replacing strings within Ionic 2 and Angular 2

I am currently working with an array of content in my JSON that includes URLs as plain text. My goal is to detect these text URLs and convert them into actual clickable links. However, I'm facing an issue where even though the URL is properly replaced ...

Combining Typescript Declarations for Express Request Object with Passport.js User/Session Integration

In my express/nodejs app, I am encountering issues with properties on the request.user object even after implementing Declaration Merging for authentication using passportjs middleware. To address this, I created a file at /types/index.d.ts in the project ...