Intellisense in VS Code is failing to work properly in a TypeScript project built with Next.js and using Jest and Cypress. However, despite this issue,

I'm in the process of setting up a brand new repository to kick off a fresh project using Next.js with TypeScript. I've integrated Jest and Cypress successfully, as all my tests are passing without any issues. However, my VSCode is still flagging some problems, which I suspect are related to an intellisense issue?

Issues observed in my Jest test files:

Issues observed in my Cypress test files:

I've come across similar problems before, but the solutions I found didn't seem to work in this case...

I've diligently followed the guidelines on how to seamlessly integrate them, including creating 2 tsconfig.json files—one in the root directory and another in the cypress directory.

./tsconfig.json:

{
    "compilerOptions": {
        "baseUrl": "./",
        "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,
        "types": ["jest", "node", "@types/testing-library__jest-dom"]
    },
    "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
    "exclude": ["node_modules", "cypress"]
}

./cypress/tsconfig.json:

{
    "extends": "../tsconfig.json",
    "compilerOptions": {
        "noEmit": true,
        // be explicit about types included
        // to avoid clashing with Jest types
        "types": ["cypress"]
    },
    "include": [
        "../node_modules/cypress",
        "../tsconfig.json",
        "../package.json",
        "./**/*.ts"
    ]
}

./cypress.config.ts:

import { defineConfig } from 'cypress';

export default defineConfig({
    e2e: {
        baseUrl: 'http://localhost:3000/',
    },
});

./jest.config.ts:

import nextJest from 'next/jest';
// Sync object
const createJestConfig = nextJest({
    // Provide the path to your Next.js app to load next.config.js and .env files in your test environment
    dir: './',
});

// Add any custom config to be passed to Jest
const customJestConfig = {
    // Add more setup options before each test is run
    setupFilesAfterEnv: ['<rootDir>/support/setupTests.js'], // if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work
    moduleDirectories: ['node_modules', '<rootDir>/'],
    testEnvironment: 'jest-environment-jsdom',
    modulePathIgnorePatterns: ['cypress'],
};

module.exports = createJestConfig(customJestConfig);

./next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
    reactStrictMode: true,
    eslint: {
        dirs: ['pages', 'public', 'styles', 'cypress', '__tests__', 'support'],
    },
};

module.exports = nextConfig;

./package.json:

{
    "name": "front-end-base-repo",
    "version": "0.1.0",
    "private": true,
    "scripts": {
        "dev": "next dev",
        "build": "next build",
        "start": "next start",
        "lint": "next lint",
        "lint:fix": "next lint --fix",
        "format": "prettier --write .",
        "prepare": "husky install",
        "precommit": "lint-staged",
        "cy:open": "cypress open",
        "cy:run": "cypress run",
        "test:cy": "start-server-and-test start http://localhost:3000 cy:run",
        "test:jest": "jest --watch",
        "test:jest:ci": "jest --ci"
    },
    "dependencies": {
        "next": "12.1.6",
        "react": "18.2.0",
        "react-dom": "18.2.0"
    },
    "devDependencies": {
        "@testing-library/jest-dom": "^5.16.4",
        "@testing-library/react": "^13.3.0",
        "@types/cypress": "^1.1.3",
        "@types/jest": "^28.1.1",
        "@types/node": "18.0.0",
        "@types/react": "18.0.12",
        "@types/react-dom": "18.0.5",
        "@types/testing-library__jest-dom": "^5.14.3",
        "@types/testing-library__react": "^10.2.0",
        "@typescript-eslint/eslint-plugin": "^5.28.0",
        "cypress": "^10.1.0",
        "eslint": "8.17.0",
        "eslint-config-next": "12.1.6",
        "eslint-config-prettier": "^8.5.0",
        "eslint-plugin-jest-dom": "^4.0.2",
        "husky": "^8.0.1",
        "jest": "^28.1.1",
        "jest-environment-jsdom": "^28.1.1",
        "lint-staged": "^13.0.1",
        "prettier": "^2.7.0",
        "start-server-and-test": "^1.14.0",
        "ts-node": "^10.8.1",
        "typescript": "4.7.3"
    }
}

For a detailed look at all the configurations, here's a link to the entire repository. I replicated the setup on another computer, only to encounter the same error in VSCode, even though all tests run smoothly.

Here's what I've discovered so far:

  • Adding
    /// <reference types="cypress" />
    at the beginning of my cypress test file resolves the issue, but incorporating
    /// <reference types="jest" />
    does not work for my jest files.
  • Creating a ./cypress/cypress.d.ts with
    /// <reference types="cypress" />
    eliminates errors in cypress tests, while having a similar file for jest like ./jest.d.ts or ./tests/jest.d.ts with
    /// <reference types="jest" />
    doesn't fix the issue for jest files. I also attempted adding other types like
    /// <reference types="@types/testing-library__jest-dom" />
  • Appending
    "typeAcquisition": { "include": ["cypress"] }
    and
    "typeAcquisition": { "include": ["jest"] }
    to the cypress and jest tsconfig.json files had no effect.

Current Status

I made edits to the file at ./cypress/support/e2e.ts to include

/// <reference types="cypress" />
, which resolved the problem with Cypress test files. However, I'm still facing VSCode errors in Jest test files.

Answer №1

To enhance Cypress, include the following code snippet in /cypress/support/e2e.ts. This will provide Cypress with type information and intellisense for all tests.

/// <reference types="cypress" />

If encountering issues with Jest expect

Omit

"**/*.ts", "**/*.tsx"
from the base tsconfig.json include section.
This entry should pertain to types rather than source files.

{
  "compilerOptions": {
    ...        
    "types": ["jest", "node", "@types/testing-library__jest-dom"]
  },
  "include": ["next-env.d.ts"],
  "exclude": ["node_modules", "cypress"]
}

index.test.tsx

expect(heading).toBeInTheDocument(); // intellisense: const expect: jest.Expect

Answer №2

Dealing with a comparable issue, I found that configuring your computer's path variable can be very beneficial. Here's how to do it: 1) Locate environment variables (you can search for this on your computer) 2) Find the path section 3) Edit and insert the location of your compiler

Answer №3

It seems like you may need to include a few extra components:

  1. typescript transformer for jest (I suggest using ts-jest since you are already utilizing ts-node).
  2. Setting up jest to utilize the transformer.

If you decide to go with ts-jest, simply add the transform configuration option:

In package.json

"jest": {
  "transform": {
    "^.+\\.tsx?$": "ts-jest"
  }
}

OR In jest.config.ts

const customJestConfig = {
  preset: 'ts-jest'
}

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

The error message "Type 'string | number' is not assignable to type 'number'" indicates a type mismatch in the code, where a value can be either

I encountered an error code while working with AngularJS to create a countdown timer. Can someone please assist me? //Rounding the remainders obtained above to the nearest whole number intervalinsecond = (intervalinsecond < 10) ? "0" + intervalinseco ...

What is the most effective way to retrieve the value of a child component in Angular 2 and pass it to the parent component?

I am working on a project with a child component (calendar) and a parent component (form). I need to select a value in the calendar and then access that value in the form component. What is the best way to achieve this? Child Component.ts: import { ...

How can I customize a Vue component slot in Storybook 8.0.6 using Vue 3.4 and Typescript to display various subcomponents within a story?

Incorporating a variety of sub-components into my Vue 3 component based on context is proving to be a challenge. Utilizing slots seems to be the solution in Vue 3, but I'm struggling to make it work within Storybook 8, which I'm using to showcase ...

Preventing recursive updates or endless loops while utilizing React's useMemo function

I'm currently working on updating a react table data with asynchronous data. In my initial attempt, the memo function doesn't seem to be called: export const DataTableComponent = (props: State) => { let internal_data: TableData[] = []; ...

Next JS now includes the option to add the async attribute when generating a list of script files

We are currently working on a nextJs application and are looking to add asynchronous functionality to all existing script tags. Despite numerous attempts, we haven't been successful in achieving this. Can anyone provide some guidance or assistance? &l ...

Angular 5 is throwing an error that says: "There is a TypeError and it cannot read the property 'nativeElement' because it

Being aware that I may not be the first to inquire about this issue, I find myself working on an Angular 5 application where I need to programmatically open an accordion. Everything seems to function as expected in stackblitz, but unfortunately, I am enco ...

Angular transforming full names to initials within an avatar

What is the best way to convert names into initials and place them inside circular icons, like shown in the screenshot below? I already have code that converts the initials, but how do we create and add them inside the icons? The maximum number of icons di ...

Define a new type in Typescript that is equal to another type, but with the added flexibility of having optional

I have 2 categories: category Main = { x: boolean; y: number; z: string } category MainOptions = { x?: boolean; y?: number; z?: string; } In this scenario, MainOptions is designed to include some, none, or all of the attributes that belong to ...

Automate the process of triggering the "Organize Imports" command on a VSCode / Typescript project through code

Is there a way to automatically run VSCode's 'Organize Imports' quickfix on every file in a project, similar to how tslint can be run programatically over the entire project? tslint --project tsconfig.json --config tslint.json --fix I want ...

To subscribe to the display of [Object Object], you cannot use an *ngIf statement without being inside an *ngFor loop

In my angular Quiz project, I have a functionality where every user can create quizzes. I want to display all the quizzes that a logged-in user has completed. Here is how I attempted to achieve this: // Retrieving user ID and category ID inside Re ...

Absolute file path reference in Node.js

I'm working on a Node.js project using WebStorm IDE. Here's the structure of my project: The root folder is named "root" and inside are 2 folders: "main" and "typings". The "main" folder has a file called "foo.ts", while the "typings" folder co ...

Pair two values from the interface

I need to extract and combine two values from an Interface: export interface CurrenciesList { currency: string; country: string; } The initial mapping looks like this: this.optionValues["currency"] = value.map(i => ({ id: i.currency, name: i.curr ...

PlateJS: Difficulty in inserting images - Screen remains empty when trying to add images using the Image Element

I incorporated the Image Element component using the command npx @udecode/plate-ui@latest add image-element This action added the caption, media-popover, and resizable components to my setup. When referencing Platejs documentation, everything appears as ...

Reduce the use of if statements

Is there a way to optimize this function by reducing the number of if statements? The currentFeatures are determined by a slider in another file. The cost is updated if the currentFeatures do not match the previousFeatures, and if the user changes it back ...

Experience the dynamic synergy of React and typescript combined, harnessing

I am currently utilizing ReactJS with TypeScript. I have been attempting to incorporate a CDN script inside one of my components. Both index.html and .tsx component // .tsx file const handleScript = () => { // There seems to be an issue as the pr ...

The ESLint setup specified in the package.json file for eslint-config-react-app is deemed to be incorrect

The property named "overrides" has the incorrect type (expected array but received {"files":["**/*.ts","**/*.tsx"],"parser":"@typescript-eslint/parser","parserOptions":{"ecmaVersion":2018,"sourceType":"module","ecmaFeatures":{"jsx":true},"warnOnUnsupported ...

Having trouble resolving the error "Cannot find name CSSTranslate" while working with VSCode and tsc? Let's tackle this issue together

My program runs smoothly in a development environment and appears flawless in VSCode, but I'm encountering issues with tsc pointing out unknown names and properties. It's puzzling because my file doesn't seem to have any problems in VSCode. ...

The correct way to type a generic React function component using TypeScript

When attempting to generalize the function component Element into a GenericElement component in TypeScript Playground, I encountered syntax issues that raised complaints from TypeScript. What is the correct method for typing a generic react function compo ...

Issue with Angular modal not opening as expected when triggered programmatically

I am working with the ng-bootstrap modal component import { NgbModal, ModalCloseReasons } from "@ng-bootstrap/ng-bootstrap"; When I click on a button, the modal opens as expected <button class="btn labelbtn accountbtn customnavbtn" ...

Utilize apexcharts to apply custom colors for negative data points

I am currently utilizing apex charts within a react application, and I have a requirement to display markers with different colors if the y value is a negative number. Below is the logic that I am using to extract the values: const colorMarkers = ...