Issue encountered: Jest-dom is throwing a TypeError because $toString is not recognized as a function on a project using Typescript, React

I have been facing a challenge while setting up jest and @testing-library/jest-dom for my typescript/react/next.js website.

Each time I try running the tests, an error occurs, and I am struggling to identify the root cause. This issue has been perplexing me for the past 3 days, and I suspect it might be related to a configuration problem.

  1. I have recreated the entire project

  2. I have uninstalled and reinstalled packages

  3. I have experimented with different config settings

No luck so far

Error:


 FAIL  __tests__/dist/button.test.js
  ● Test suite failed to run

    TypeError: $toString is not a function

    > 1 | import '@testing-library/jest-dom'
        | ^

      at isArguments (node_modules/is-arguments/index.js:12:9)
      at node_modules/is-arguments/index.js:28:9
      at Object.<anonymous> (node_modules/is-arguments/index.js:29:2)
      at Object.<anonymous> (node_modules/deep-equal/index.js:10:19)
      at Object.<anonymous> (node_modules/aria-query/lib/elementRoleMap.js:7:41)
      at Object.<anonymous> (node_modules/aria-query/lib/index.js:10:46)
      at Object.<anonymous> (node_modules/@testing-library/jest-dom/dist/to-be-checked.js:8:18)
      at Object.<anonymous> (node_modules/@testing-library/jest-dom/dist/matchers.js:203:20)
      at Object.<anonymous> (node_modules/@testing-library/jest-dom/dist/extend-expect.js:3:42)
      at Object.<anonymous> (node_modules/@testing-library/jest-dom/dist/index.js:3:1)
      at Object.<anonymous> (jest-setup.ts:1:1)

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "baseUrl": ".",
    "noFallthroughCasesInSwitch": true,
    "outDir": "./dist",
    "paths": {
      "@/*": ["./*"]
    },
  },
   "compileOnSave": true,
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "babel.config.js", "jest-setup.ts", "jest.config.ts"],
  "exclude": ["node_modules"]
}

jest.config.ts

import type { Config } from "@jest/types";

const config: Config.InitialOptions = {
  preset: "ts-jest",
  testEnvironment: "node",
  extensionsToTreatAsEsm: ['.ts'],
  verbose: true,
  automock: true,
  transformIgnorePatterns: ['node_modules/', '^.+\\.module\\.(css|sass|scss)$'],
  moduleFileExtensions: ["js", "jsx", "ts", "tsx"],
  moduleDirectories: ["node_modules", "src"],
  moduleNameMapper: {
    "\\.(css|less|scss)$": "identity-obj-proxy"
  },
  transform: {
    '^.+\\.(ts|tsx)?$': 'ts-jest',
    '^.+\\.(js|jsx)$': 'babel-jest',
    
  },
  setupFilesAfterEnv: ['<rootDir>/jest-setup.ts'],
}

export default config;

jest-setup.ts

--> import '@testing-library/jest-dom'

babel.config.js

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

Answer №1

If you are using Next.js, the Jest configuration should be set up as follows:

/// jest.config.ts

import nextJest from 'next/jest'

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

const customJestConfig = {
  setupFilesAfterEnv: ['./support/jest.setup.ts'],
  setupFiles: [
    "./support/environment.ts"
  ],
  moduleDirectories: ['node_modules', '<rootDir>/'],
  testEnvironment: 'jest-environment-jsdom',
}

export default createJestConfig(customJestConfig)

where

/// ./support/jest.setup.ts

// Optional: configure or set up a testing framework before each test.
// If you delete this file, remove `setupFilesAfterEnv` from `jest.config.ts`

// Used for __tests__/testing-library.js
// Learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom/extend-expect'

/// ./support/environment.ts

process.env.AUTH0_SECRET = 'session_secret';
process.env.AUTH0_ISSUER_BASE_URL = 'https://acme.auth0.local';
process.env.AUTH0_BASE_URL = 'http://www.allstars.com/';
process.env.AUTH0_CLIENT_ID = 'client_id';
process.env.AUTH0_CLIENT_SECRET = 'client_secret';

export {}

/// tsconfig.json

...
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
...

No need to include "babel.config.js", "jest-setup.ts", "jest.config.ts" in tsconfig.json. Babel is not required at all. The Jest configs can be excluded as well.

I encountered a similar error message and found that the above configuration worked for me.

This setup uses Next.js with Typescript and Jest to facilitate testing of React components without the need for Babel.

Answer №2

Dealing with a similar problem, I found a solution without the need for Next.js

In my case, tweaking the jest.config.js file and changing the automock: false setting did the trick.

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

Guide to turning off the previous button in FullCalendar using Angular 7 and TypeScript

Can someone help me with disabling the previous button on FullCalendar if I go back 2 months? For example, if it's currently April and I navigate to February, I want the previous button to be disabled. I have FullCalendar implemented, but all the sol ...

Utilizing Typescript Generics in Arrow Function to Combine Two Arguments

For instance, I am working with this code in a .tsx file extension const Add = <T,>(arg0: T, arg1: T): T => arg0 + arg1; const A = Add(1, 2); const B = Add('1', '2') However, I am encountering an issue, as there is an error m ...

Issues with relocating function during the NgOnInit lifecycle hook in an Angular 2 application

Currently, I am facing an issue with my Angular 2 app where the data sometimes lags in populating, causing a page component to load before the information is ready to display. When this happens, I can manually refresh the page for the data to appear correc ...

What is the recommended TypeScript type for the NextJS _app.tsx Component and pageProps?

Take a look at the default _app.tsx code snippet from NextJS: function MyApp({ Component, pageProps }) { return ( <Component {...pageProps} /> ) } The issue arises when transitioning to TypeScript, as ES6Lint generates a warning indicating t ...

Managing data with Angular 2: Setting and retrieving values

In my current project, I am working on developing a service that can parse data to different components based on various routes. When I call this service within the same component, everything works as expected and I get the desired results. However, when ...

Advancement of server-side actions in NextJs 13 or 14 can now be tracked in

Is there a method to notify the client of status updates during server actions in NextJs 13 or 14? For example, if you have a server action that involves processing 1000 database records, how can you display the progress of this activity to the client? ...

What is causing this error/bug to show up in Angular?

I encountered an error while working on my Angular project that incorporates both front-end and back-end development with Python Flask. Even though the page updates correctly, a database-related error is being displayed in the console. Below are the snippe ...

Typescript: The .ts file does not recognize the definition of XMLHttpRequest

I have encountered an issue with a .ts file containing the following code: var xhttp = new XMLHttpRequest(); After running the grunt task to compile the ts files using typescript, no errors were reported. However, when I attempt to instantiate the class ...

Ways to effectively utilize an interface incorporating props.children and other property varieties

Currently working on a project with Next.js and Typescript. In order to create a layout component, I defined the following interface: export interface AuxProps { children: React.ReactNode; pageTitle: 'string'; } The layout component code sn ...

What is the best way to merge two approaches for tallying items within each category?

I have an Angular 8 application that includes two methods for displaying the number of items in each category. These items are retrieved from the back-end and are categorized as follows: <mat-tab> <ng-template mat-tab-label> ...

Having trouble testing firebase messaging on my local server

I've encountered an issue while trying to retrieve a token from firebase/messaging for use in notifications. The error message "messaging/unsupported-browser" (FirebaseError: Messaging: This browser doesn't support the API's required to use ...

Generating a Dynamic Sitemap for Strapi and Next.js

I am currently working on creating a sitemap for my NextJs application using the strapi-sitemap-plugin developed by boazpoolman. The challenge I am facing is with a nested dynamic route structure like this: /articles/[categories]/[article] With the plugi ...

Angular Http Promise is not returning the expected value

Struggling to update my component property with an HTTP result, but encountering issues. Thank you for your assistance! (currently using a static mock object) Class - Object export class Gallery { name: string; } Service import { Injectable } from ...

Incorporate Typescript into specific sections of the application

I've got a Node.js application that's entirely written in JavaScript. However, there are certain sections of my app where I'd like to utilize TypeScript interfaces or enums. Is there a way for me to incorporate Typescript into only those s ...

I am looking to personalize a Material UI button within a class component using TypeScript in Material UI v4. Can you provide guidance on how to achieve this customization?

const styling = { base: { background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)', border: 0, borderRadius: 3, boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)', color: 'white', height: 48, ...

Angular 14 Observables are not triggering resize events

There seems to be an issue here, as the code is not being triggered at all. The console log is not printing and this.width is not changing. constructor(private host: ElementRef, private zone: NgZone) {} public ngOnInit(): void { this.observer = new Re ...

The functionality of the System JS map is not functioning properly

Despite the challenges I face with System.js, I find it to be a valuable tool that I prefer over alternatives. This is my current System.js configuration: System.config({ packages: { app: { format: 'register' ...

Test fails in Jest - component creation test result is undefined

I am currently working on writing a Jest test to verify the creation of a component in Angular. However, when I execute the test, it returns undefined with the following message: OrderDetailsDeliveryTabComponent › should create expect(received).toBeTru ...

Tips for streamlining responses for the latest create-next-app version

After running npx create-next-app@latest, a series of questions are prompted that disrupt our docker pipeline automation. Is there a way to automate the response to these questions? Currently, we have this command in our Dockerfile: RUN npx --yes create- ...

Prisma Date and Time Formatting Challenge

Exploring Nest Js and prisma led me to the need to store DateTime data in my database based on my timezone preferences. joining DateTime @db.Timestamptz(5) ` I found that using @db.Timestamptz resolved my timezone storage issue, but upon retriev ...