Cypress tests not recognizing node_modules package types
Asked Answered
E

1

9

I'm having trouble with my Cypress tests for my (Typescript) application recognizing types for package I've installed. Here is my top-level directory structure:

cypress
node_modules
src

My cypress/tsconfig.json file looks like this:

{
  "compilerOptions": {
    "strict": true,
    "baseUrl": "../node_modules",
    "paths": {
      "~/*": ["../src/*"]
    },
    "jsx": "react",
    "target": "es6",
    "lib": ["es6", "dom", "es2017.string"],
    "types": ["cypress"]
  },
  "include": ["**/*.ts"]
}

In one of my spec files, I have the following imports:

import * as faker from 'faker';
import { DeepPartial } from 'utility-types';

The types for faker are defined in DefinitelyTypes (@types/faker) whereas the types for utility-types are included as *.d.ts files in that package. The faker import has no problem, but the utility-types import is giving a Cannot find module 'utility-types' or its corresponding type declarations. error.

I've tried explicitly including the *.d.ts files from the node_modules directory to the tsconfig.json file under compilerOptions.types, compilerOptions.typeRoots, and include properties, but to no avail.

I also created "fake" (?) types like the following so it will compile:

declare module 'utility-types' {
  export type DeepPartial<T> = {};
}

This allows for the app to compile AND, at run-time, the packages are resolved so it appears the issue is with finding the types, not the modules themselves.

Why is Cypress not finding the types for these packages?

Emotion answered 4/9, 2020 at 14:16 Comment(3)
Try adding the following to your .tsconfig: "include": [ "node_modules/cypress/types/index.d.ts", "node_modules/cypress/types/blob-util.d.ts", "node_modules/cypress/types/minimatch.d.ts", "node_modules/cypress/types/bluebird.d.ts", "cypress/**/*.ts" ]Manipulate
For reference, I looked at a sample repo with a working TS environment: github.com/cypress-io/cypress-example-recipes/blob/master/…Manipulate
@RaghavKukreti I should have mentioned I tried the include tsconfig property in addition to types and typeRoots. It does not work.Emotion
R
3

You can try to set moduleResolution to node

https://www.typescriptlang.org/docs/handbook/module-resolution.html#module-resolution-strategies

I have tried to import utility-types with this configuration: the import works, and test run correctly

{
    "compilerOptions": {
      "strict": true,
      "baseUrl": "../node_modules",
      "paths": {
        "~/*": ["../src/*"]
      },
      "jsx": "react",
      "target": "es6",
      "lib": ["es6", "dom", "es2017.string"],
      "types": ["cypress"],
      "moduleResolution": "node"
    },
    "include": ["**/*.ts"]
  }
Robbert answered 16/9, 2020 at 9:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.