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

Guide to showcasing JSON Array in an HTML table with the help of *NgFor

Struggling to showcase the data stored in an array from an external JSON file on an HTML table. Able to view the data through console logs, but unable to display it visually. Still navigating my way through Angular 7 and might be overlooking something cruc ...

Trouble encountered when using RxJS zip and pipe together

In my Angular Resolver, I am facing a scenario where I need to wait for two server calls. The catch is that the second server call is optional and can be skipped based on user input. This data retrieval process is crucial for loading the next page seamless ...

Issue with Ionic2 radio button selection not persisting

I'm currently working on implementing Radio Alerts within an Ionic2 application. To create a radio alert, I used the following code snippet: let alert = this.alertCtrl.create(); alert.setTitle('Select a Radio Alert'); alert.addInput({ typ ...

A Typescript type that verifies whether a provided key, when used in an object, resolves to an array

I have a theoretical question regarding creating an input type that checks if a specific enum key, when passed as a key to an object, resolves to an array. Allow me to illustrate this with an example: enum FormKeys { x = "x", y = "y&q ...

Is it possible to access NgbdModalContent properties from a different component?

If I have a component with a template containing an Edit button. When the user clicks on it, I want to load another component as a dynamic modal template. The component is named ProfilePictureModalComponent and it includes the Edit button: (Angular code h ...

Adding properties to a class object in Javascript that are integral to the class

Recently, I've been contemplating the feasibility of achieving a certain task in JavaScript. Given my limited experience in the realm of JavaScript, I appreciate your patience as I navigate through this. To illustrate what I am aiming for, here' ...

Creating a data structure that consists of pairs of elements, inspired by the alignment of domino bricks, using TypeScript syntax

My goal is to establish a type alias in TypeScript that allows all values which are arrays of Domino pairs, where each pair connects like domino bricks: Pair<A,B> connects with Pair<C,D> only if B = C. For example: const chain1: DominoChain = ...

Issues arising post transitioning to 14.0.0 from 13.0.0 version of ngx-masonry library leading to failed tests

Following the update to the latest stable version of the library ngx-masonry 14.0.0, our tests started failing. The release was just yesterday (24.10.2022) and you can find the changelog here: https://github.com/wynfred/ngx-masonry/blob/master/CHANGELOG.md ...

Typescript - Issue with accessing Express Response object

Having trouble using the methods of the Response object in my TypeScript method. When I try to log it, all I get is an empty object. It seems like the import is not providing the response as expected. import { Response } from 'express'; async sen ...

When the button is clicked, (ngSubmit) will be triggered

In my Angular2 Form Component, I have implemented two buttons with different functionalities. Button Submit: This button submits all the values to the API. Button Add: This button adds an object to an array. Here are the two methods: onSubmit() { this. ...

Vue Component Unit Testing: Resolving "Unexpected Identifier" Error in Jest Setup

Having just started using Jest, I wanted to run a simple unit test to make sure everything was set up correctly. However, I encountered numerous errors during compilation while troubleshooting the issues. When running the test suite, Jest successfully loc ...

How do I define two mutations in a single component using TypeScript and react-apollo?

After exploring this GitHub issue, I have successfully implemented one mutation with Typescript. However, I have been unable to figure out how to use 2 mutations within the same component. Currently, there is only a single mutate() function available in t ...

Can a generic type be utilized to instantiate an object?

In my code, I have a class named Entity as shown below: class Entity { constructor(readonly someValue: string) {} someFunction() {} } Now, I am trying to create a class that will handle these entities and be able to create instances of them. In or ...

Loop within a promise results in undefined

Within my application, there is a function that returns a promise. Inside this function, I wait for an image in the DOM to become available and then extract that element to generate base64 data from it. getCodesOfOneMerchant(merchantDataEntry: MerchantData ...

Executing Typescript build process in VSCode on Windows 10 using Windows Subsystem for Linux

My configuration for VSCode (workspace settings in my case) is set up to utilize bash as the primary terminal: { "terminal.integrated.shell.windows": "C:\\WINDOWS\\Sysnative\\bash.exe" } This setup allo ...

Using function overloading in TypeScript causes an error

I'm currently exploring the concept of function overloading in TypeScript and how it functions. type CreateElement = { (tag: 'a'): HTMLAnchorElement (tag: 'canvas'): HTMLCanvasElement (tag: 'table'): HTMLTableElem ...

Navigating through the concept of passing objects by reference in child components of Angular 2+

Understanding that TypeScript uses object passing by reference can be challenging, especially when dealing with deep copy issues. This becomes particularly cumbersome when working within a theme. I recently encountered an issue with a component containing ...

The term 'EmployeeContext' is being utilized as a namespace in this scenario, although it actually pertains to a type.ts(2702)

<EmployeeContext.Provider> value={addEmployee, DefaultData, sortedEmployees, deleteEmployee, updateEmployee} {props.children}; </EmployeeContext.Provider> I am currently facing an issue mentioned in the title. Could anyone lend a hand? ...

How to turn off automatic password suggestions in Chrome and Firefox

Currently, I have integrated a 'change password' feature which includes fields for 'old password', 'new password', and 'retype password'. However, the autocomplete feature is suggesting passwords from other user acco ...

Leverage Sinon's fakeServer in combination with promises and mocha for efficient

Having an issue here: I need to test a method that involves uploading data to an AWS S3 bucket. However, I don't want the hassle of actually uploading data each time I run my tests or dealing with credentials in the environment settings. That's w ...