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

Avoid accessing invariant variables when mocking: __extends

I'm currently in the process of converting a collection of react components from JavaScript to TypeScript, and I've encountered an issue with jest.mock(). Before: "react": "^15.6.1" "jest": "20.0.4" "enzyme": "^2.9.1" CustomDate.js ... import ...

When you type a letter in the middle of a string, the cursor is automatically moved back to the end - Material UI

I designed a ChipInput feature that switches to a string when focused and transforms into a Chip component when blurred, with chips separated by commas. Everything seems to be functioning properly except for one issue I am encountering. Whenever I type in ...

The value object is not utilized to override default properties within a context

As I begin setting up a basic NextJS 14 app, I plan to utilize some properties globally by creating a global context named AppContext. This will allow me to access general data such as user information and the overall state of the application. Here is the ...

Discovering the object and its parent within a series of nested arrays

Is there a way to locate an object and its parent object within a nested array of unknown size using either lodash or native JavaScript? The structure of the array could resemble something like this: name: 'Submodule122'</p> I have been ...

What steps are involved in setting up a SAML service provider using @node-saml/node-saml?

I'm currently working on a SAML SP implementation using the @node-saml/node-saml library. Despite creating the necessary source code, I am facing an issue with the SAML authentication not functioning as expected. Can anyone provide guidance on how to ...

Mastering Typing for Enhanced Order Components using Recompose and TypeScript

I have been working on integrating recompose into my react codebase. As part of this process, I have been experimenting with getting some basic functionality to work. While I have made progress, I am uncertain if I am following the correct approach for usi ...

When canActivate returns false, the screen in Angular 2 will still be accessed

I am encountering a problem where my canActivate method is returning false, but still navigating to the blocked screen. This issue seems to only occur in Chrome, as everything works fine in IE. Here is how the canActivate method looks: canActivate(route: ...

Struggling to locate the string connected to the JSON file while performing translation tasks (i18n)

After successfully translating many pages on my website project, I encountered an issue while trying to translate specific components that were created. The error message reads: "TypeError: Cannot read properties of undefined (reading 'titulo')" ...

I encountered an issue with Typescript Jest where it was unable to find the mock or mockReturnedValue functions on the types I

Let's test out this interesting class: //RequestHandler.js import axios, {AxiosInstance} from 'axios'; import settings from './settings'; const axiosHandler: AxiosInstance = axios.create({ baseURL: 'http://localhost:8081&a ...

Oops! The basePath must always begin with a forward slash "/", but it looks like it starts with a period "." instead. This error was encountered

I am encountering an issue while trying to include '.' in my baseurl. The error message indicates: Error: Specified basePath has to start with a /, found "." const nextConfig = { basePath: '.', reactStrictMode: true, ...

Dealing with Unexpected Timeout Errors and Memory Leaks in Express/Typescript Using Jest, Supertest, and TypeORM

Currently, I am in the process of writing unit tests for an express API. Each test suite initiates a fresh instance of an express server before running the tests. Individually, each test suite runs smoothly without any problems. However, when executed tog ...

What is the best way to upload an entire folder instead of individual files on my Next app?

I am currently working on a new application where I can upload files using the fileAPI. My goal is to upload an entire folder and create a logic to extract and store all types of files (.txt, .img, .pdf) within that folder on the frontend. While I have su ...

Pause until the user selects either the confirm or deny option before proceeding with the next action

As a beginner in Angular, I am seeking help with my code structure. I have three files: WarningComponent (which displays a warning modal using Bootstrap), modalService (responsible for opening modals), and votingComponent. Within the votingComponent, ther ...

What is the best way to handle success data in React Query?

Currently, I have an API call function (using httpClient as axios instance) interface IRegisterResponse { accessToken: string; } export const register = async ({ name, password, token, }: IRegisterParams) => await httpClient.post<IRegiste ...

Issues with Next.js and Framer Motion

My component is throwing an error related to framer-motion. What could be causing this issue? Server Error Error: (0 , react__WEBPACK_IMPORTED_MODULE_0__.createContext) is not a function This error occurred during page generation. Any console logs will be ...

The concept of nesting partial types in Typescript

Struggling to type partial objects from GraphQL queries, especially with an object that looks like this... // TypeScript types interface Foo { bar: Bar } interface Bar { a: number, b: number } // GraphQL query foo { bar { a // 'b&a ...

Underscore.js is failing to accurately filter out duplicates with _uniq

Currently, I am integrating underscorejs into my angular project to eliminate duplicate objects in an array. However, I have encountered an issue where only two string arrays are being kept at a time in biddingGroup. When someone else places a bid that is ...

Synchronization issues arise when attempting to update the localStorage

Whenever I switch to dark mode, the update doesn't reflect in _app unless I have two tabs opened and trigger it in one tab. Then, the other tab gets updated with dark mode toggled, but not the tab where I pressed the toggle. I am using useSettings in ...

Vue-Apollo - The 'value' property is not present in the 'Readonly<Ref<Readonly<any>>>' type

MY CURRENT DILEMMA: In my quest to seamlessly integrate vue-apollo v4 with Typescript, I have encountered a challenge. I am in the process of retrieving data from a simple query using useQuery along with useResult. The default return type of useResult i ...

``Changing the value of a class variable in Angular 2 does not result in the

I am facing an issue with a component that contains a variable called myName export class ConversationComponent implements OnInit { private myName: string; showNames(name) { this.myName=name; } } The value is assigned using the showNames() m ...