Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tests fail to run in watch mode #8534

Closed
NileDaley opened this issue Jun 5, 2019 · 22 comments
Closed

Tests fail to run in watch mode #8534

NileDaley opened this issue Jun 5, 2019 · 22 comments

Comments

@NileDaley
Copy link

NileDaley commented Jun 5, 2019

🐛 Bug Report

My tests run just fine when using the jest command. However, as soon as I run jest --watch I get the following error.

Configuration error:
    
    Could not locate module @/types/keyboard mapped as:
    /Users/niledaley/Code/project/src/renderer/types/keyboard.
    
    Please check your configuration for these entries:
    {
      "moduleNameMapper": {
        "/@\/(.*)$/": "/Users/niledaley/Code/project/src/renderer/$1"
      },
      "resolver": null
    }

Here's a tree of my src/renderer/types folder:

src/renderer/types
├── api.d.ts
├── cart.d.ts
├── checkout.d.ts
├── filters.d.ts
├── index.d.ts
├── keyboard.d.ts
├── modules.d.ts
├── payment.d.ts
├── product.d.ts
├── productlist.d.ts
├── settings.d.ts
└── thunk.d.ts

My jest.config.js file contains the following:

module.exports = {
    preset: 'ts-jest',
    testEnvironment: 'node',
    moduleNameMapper: {
        '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
            '<rootDir>/__mocks__/fileMock.js',
        '\\.(css|scss)$': 'identity-obj-proxy',

        // Tell jest to look in the src dir when we use @/
        '@/(.*)$': '<rootDir>/src/renderer/$1',
    },
    setupFilesAfterEnv: ['./jest.setup.js'],
    globals: {
        window: {},
    },
    watchPathIgnorePatterns: [
        '<rootDir>/node_modules/',
        '<rootDir>/src/renderer/utils/setNativeValue.ts',
    ],
    coveragePathIgnorePatterns: [
        '<rootDir>/node_modules/',
        '<rootDir>/src/renderer/utils/setNativeValue.ts',
    ],
};

And my tsconfig.json file looks like this:

{
    "extends": "./node_modules/electron-webpack/tsconfig-base.json",
    "compilerOptions": {
        "allowSyntheticDefaultImports": true,
        "esModuleInterop": true,
        "jsx": "react",
        "baseUrl": ".",
        "paths": {
            "@/*": ["src/renderer/*"],
            "@public/*": ["public/*"]
        },
        "module": "es2015",
        "moduleResolution": "node",
        "noImplicitAny": true,
        "noImplicitThis": true,
        "strictNullChecks": true,
        "sourceMap": true,
        "target": "esnext"
    },
    "exclude": ["node_modules"]
}

Jest version: "^24.5.0",
ts-jest version: "^24.0.0",
typescript version: "^3.4.5"

@NileDaley
Copy link
Author

I've also just noticed that I can get watch mode to work in the following situation:

  1. There are no changes since the last commit
  2. I run jest --watch
  3. Jest says that there are no changes since the last commit
  4. I press a to re-run all tests
  5. A full test run will be performed
  6. I change a file
  7. A test run will be triggered

@NileDaley
Copy link
Author

I've made a repo in which you can reproduce this issue:

https://github.com/NileDaley/jest-watch-mode-issue

@jeysal
Copy link
Contributor

jeysal commented Jun 8, 2019

Your repo works fine for me with both --watch / press a and --watchAll
image

@NileDaley
Copy link
Author

I've tested on 2x macOS devices and 1x windows device and --watch produces the original error on each. However, --watchAll seems to be working so I can use that as a work-around for now.

@aczekajski
Copy link

aczekajski commented Jun 19, 2019

Our whole team has the same issue. Tests are running ok when we run all tests with jest command but often fail when running jest --watch. The same happens when I do jest someFilename or jest --findRelatedTests someFilename or jest --changedSince develop. The only solution found is to delete jest cache folder.

Error:

Configuration error:

    Could not locate module ~/modules/product/productCard/productCardType mapped as:
    C:\Users\ac\NewWeb\src\modules/product/productCard/productCardType.

    Please check your configuration for these entries:
    {
      "moduleNameMapper": {
        "/^~(\\|\/)(.*)$/": "C:\Users\ac\NewWeb\src\$2"
      },
      "resolver": null
    }

      at createNoMappedModuleFoundError (node_modules/jest-resolve/build/index.js:472:17)
          at Array.reduce (<anonymous>)
      at SearchSource.findRelatedTests (node_modules/@jest/core/build/SearchSource.js:280:30)
      at SearchSource.findTestRelatedToChangedFiles (node_modules/@jest/core/build/SearchSource.js:363:14)

My jest.config.js:

module.exports = {
   transform: {
      '^.+\\.tsx?$': 'ts-jest',
      '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '<rootDir>/__mocks__/filePathMock.js',
   },
   testRegex: '(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$',
   testPathIgnorePatterns: ['node_modules', 'e2e'],
   moduleFileExtensions: [
      'ts',
      'tsx',
      'js',
      'json',
   ],
   moduleNameMapper: {
      '\\.(css|less|sass|scss)$': 'identity-obj-proxy',
      '\\.svg\\?inline$': '<rootDir>/__mocks__/svgMockModule.js',
      '(.*)\\.svg\\?external$': '$1.svg',
      '^~(\\\\|/)(.*)$': '<rootDir>/src/$2',
   },
   setupFilesAfterEnv: ['<rootDir>/jest.enzyme.config.ts'],
   setupFiles: [
      '<rootDir>/__mocks__/shims.js',
      '<rootDir>/jest.enzyme.config.ts',
      '<rootDir>/__mocks__/webpackDefines.js',
      '<rootDir>/__mocks__/localstorage.js',
   ],
   cacheDirectory: '<rootDir>/.jest-cache',
   coveragePathIgnorePatterns: [
      '/*.svg',
      '/node_modules/',
   ],
   snapshotSerializers: [
      'enzyme-to-json/serializer',
   ],
   watchPathIgnorePatterns: ['backstop_data'],
   reporters: ['default', 'jest-html-reporter', 'jest-junit'],
   coverageReporters: ['cobertura', 'html'],
   globals: {
      'ts-jest': {
         tsConfig: '<rootDir>/tsconfig-ts-jest.json',
      },
   },
};

Jest version: 23.6.0 and 24.8.0
OS: Windows 10 pro

@aczekajski
Copy link

@NileDaley @jeysal I couldn't reproduce the error with the repo from #8534 (comment) using --watch. But this works for me:

  1. Clone that repo and install packages with yarn
  2. Make any irrelevant change in keyboard.ts file (for example add a comment)
  3. Run yarn test --changedSince master
Configuration error:

Could not locate module @/types/keyboard mapped as:
C:\Users\ac\jest-watch-mode-issue\src\renderer\types/keyboard.

Please check your configuration for these entries:
{
  "moduleNameMapper": {
    "/@\/(.*)$/": "C:\Users\ac\jest-watch-mode-issue\src\renderer\$1"
  },
  "resolver": null
}
    at createNoMappedModuleFoundError (C:\Users\ac\jest-watch-mode-issue\node_modules\jest-resolve\build\index.js:472:17)
    at Resolver.resolveStubModuleName (C:\Users\ac\jest-watch-mode-issue\node_modules\jest-resolve\build\index.js:433:21)
    at Resolver.getMockModule (C:\Users\ac\jest-watch-mode-issue\node_modules\jest-resolve\build\index.js:275:31)
    at dependencies.reduce (C:\Users\ac\jest-watch-mode-issue\node_modules\jest-resolve-dependencies\build\index.js:67:45)
    at Array.reduce (<anonymous>)
    at DependencyResolver.resolve (C:\Users\ac\jest-watch-mode-issue\node_modules\jest-resolve-dependencies\build\index.js:53:25)
    at DependencyResolver.resolveInverseModuleMap (C:\Users\ac\jest-watch-mode-issue\node_modules\jest-resolve-dependencies\build\index.js:175:30)
    at DependencyResolver.resolveInverse (C:\Users\ac\jest-watch-mode-issue\node_modules\jest-resolve-dependencies\build\index.js:198:17)
    at SearchSource.findRelatedTests (C:\Users\ac\jest-watch-mode-issue\node_modules\@jest\core\build\SearchSource.js:280:30)
    at SearchSource.findTestRelatedToChangedFiles (C:\Users\ac\jest-watch-mode-issue\node_modules\@jest\core\build\SearchSource.js:363:14)

@jeysal
Copy link
Contributor

jeysal commented Jun 19, 2019

Alright, I can reproduce that. I believe the reason why this occurs is that .d.ts is not a known extension. When running the test this is not a problem because the import is just used as a type and thus stripped out, but when using something like --changedSince, the problem occurs when Jest looks at the module dependencies to find affected tests. The immediate fix here would be to configure moduleFileExtensions: ["js", "ts", "d.ts"], but I'm not sure if this might cause other problems somewhere.

@aczekajski
Copy link

@jeysal Isn't d.ts just a subset of ts and thus included anyway, even without adding d.ts to moduleFileExtensions?

@jeysal
Copy link
Contributor

jeysal commented Jun 25, 2019

Jest does not use tsc for TS support, only ts-jest does.

@geyuqiu
Copy link

geyuqiu commented Aug 25, 2019

Having a similar error message after deleting a source file and commenting everywhere the source file is referenced. While running jest in watch mode, this error is produced, however jest without watch, runs successfully. Somehow jest caches and wanted to imported the deleted source file ?

@kelly-tock
Copy link

I have found in jest watch mode if I'm changing branches sometimes it thinks something is there that isn't there anymore, and throws a similar error message. I sometimes just have to delete node modules and re-install to get it to work.

@gersomvg
Copy link

The immediate fix here would be to configure moduleFileExtensions: ["js", "ts", "d.ts"], but I'm not sure if this might cause other problems somewhere.

This indeed solved it @jeysal !

@ahnpnl
Copy link
Contributor

ahnpnl commented Feb 16, 2020

hi, I came from an issue in ts-jest related to jest watch mode and cache. Basically I have the scenario:

thing.ts contains:

export type Thing = {
	a: number;
	// b: number;
};

thing.test.ts contains:

import { Thing, doTheThing } from "./thing";

// See the Thing definition.  Changing the type definition should result in a compile failure here.
export const thing: Thing = { a: 1 };

describe("Thing", () => {
  it("should do the thing", () => {
      expect(doTheThing()).toEqual(3);
  });
});
  • 1st run, test passes and jest caches.
  • Modifying thing.ts by uncommenting b: number, test passes but actually it shouldn't. In the 2nd run, jest detects only thing.ts has changed but not all references to thing.ts therefore tests still pass.

I wonder if this is something jest can solve. It would be great.

@hudsontavares
Copy link

Guys, I am not sure if that issue stills haunting someone, but in my case, the issue was the existence of the coverage folder (seems like Jest looks at it for --watch mode) - it should also apply to whatever location you set the coverage reports to be stored.

If the modules described there are somehow different from your current file structure, there is a chance to see this annoying issue. Deleting the forenamed folder did the trick and made the watch mode work great as usual.

@ACollectionOfAtoms
Copy link

ACollectionOfAtoms commented Mar 19, 2020

+1 this bug. We are currently running into it. .d.ts files and coverage directories seem unrelated to us (although we are using TS). From what we can determine it has something to do with the diff generated by the --changedSince or --watch options

@mctrafik
Copy link

mctrafik commented May 8, 2020

Having this failure, too. :( So annoying.

Tests pass when running jest

If I add --watch

It fails:

Configuration error:
    
    Could not locate module src/path/to/MyModule mapped as:
    /full/path/to/MyModule.
    
    Please check your configuration for these entries:
    {
      "moduleNameMapper": {
        "/^src\/(.*)/": "/full/path/prefix/src/$1"
      },
      "resolver": null
    }

Tests break if I add "d.ts" as a module extension!

Using --watchAll works.

Package versions:

    "jest": "24.9.0",
    "jest-circus": "^24.9.0",
    "ts-jest": "24.3.0",
    "typescript": "3.8.3",

jest config:

const wdio = '<rootDir>/src/webdriver';

module.exports = {
  globals: {
    'ts-jest': {
      tsConfig: '<rootDir>/tsconfig.wdio.json',
      diagnostics: false,
    },
  },
  moduleFileExtensions: [
    "ts",
    "tsx",
    "js",
    "node",
  ],
  // This should be the default behavior, but without this imports don't work. :(
  moduleNameMapper: {
    "^src/(.*)": "<rootDir>/src/$1"
  },
  testEnvironment: 'node', 
  testRunner: "jest-circus/runner",
  testRegex: '.*\\.wdio(\\.[^.]+)?\\.ts$',
  setupFilesAfterEnv: [`<rootDir>/build/beforeTestFile.js`],
  preset: 'ts-jest',
  transform: {
    '^.+\\.(js|jsx|mjs)$':
    '<rootDir>/node_modules/react-scripts-ts/config/jest/babelTransform.js',
  },
  testEnvironment: `<rootDir>/build/webdriverEnvironment.js`,
  testEnvironmentOptions: { ..unrelated.. },
  testTimeout: 5 * 60 * 1000, // 5 minutes in milliseconds.
  testURL: 'http://localhost:3000',
  verbose: true,

@SHaTRO
Copy link

SHaTRO commented Mar 25, 2021

Very strange failure trying to use a shim on JSON for BigInt. I put this shim in setupFiles:
BigInt.prototype.toJSON = function() { return this.toString() };

Running just jest works great if I have a test failure on .toEquals(BigInt(100), every time - the shim prevents the classic "Do not know how to serialize BigInt" error.

Running jest --watchAll works for a while then fails and can fail catastrophically (uncaught promise rejection) and it gets stuck. Quite strange.

This blog posts describes almost exactly the same issue in some detail: https://realonetech.wordpress.com/2021/03/24/jest-custom-matcher-in-typescript/

@Xor-el
Copy link

Xor-el commented May 26, 2021

@SHaTRO , +1 on your report, I faced exactly the same issue you pointed out.
it seems the only valid way to work around this for now is to write your own custom matcher for bigint.

@minademian
Copy link

Our whole team has the same issue. Tests are running ok when we run all tests with jest command but often fail when running jest --watch. The same happens when I do jest someFilename or jest --findRelatedTests someFilename or jest --changedSince develop. The only solution found is to delete jest cache folder.

Error:

Configuration error:

    Could not locate module ~/modules/product/productCard/productCardType mapped as:
    C:\Users\ac\NewWeb\src\modules/product/productCard/productCardType.

    Please check your configuration for these entries:
    {
      "moduleNameMapper": {
        "/^~(\\|\/)(.*)$/": "C:\Users\ac\NewWeb\src\$2"
      },
      "resolver": null
    }

      at createNoMappedModuleFoundError (node_modules/jest-resolve/build/index.js:472:17)
          at Array.reduce (<anonymous>)
      at SearchSource.findRelatedTests (node_modules/@jest/core/build/SearchSource.js:280:30)
      at SearchSource.findTestRelatedToChangedFiles (node_modules/@jest/core/build/SearchSource.js:363:14)

My jest.config.js:

module.exports = {
   transform: {
      '^.+\\.tsx?$': 'ts-jest',
      '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '<rootDir>/__mocks__/filePathMock.js',
   },
   testRegex: '(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$',
   testPathIgnorePatterns: ['node_modules', 'e2e'],
   moduleFileExtensions: [
      'ts',
      'tsx',
      'js',
      'json',
   ],
   moduleNameMapper: {
      '\\.(css|less|sass|scss)$': 'identity-obj-proxy',
      '\\.svg\\?inline$': '<rootDir>/__mocks__/svgMockModule.js',
      '(.*)\\.svg\\?external$': '$1.svg',
      '^~(\\\\|/)(.*)$': '<rootDir>/src/$2',
   },
   setupFilesAfterEnv: ['<rootDir>/jest.enzyme.config.ts'],
   setupFiles: [
      '<rootDir>/__mocks__/shims.js',
      '<rootDir>/jest.enzyme.config.ts',
      '<rootDir>/__mocks__/webpackDefines.js',
      '<rootDir>/__mocks__/localstorage.js',
   ],
   cacheDirectory: '<rootDir>/.jest-cache',
   coveragePathIgnorePatterns: [
      '/*.svg',
      '/node_modules/',
   ],
   snapshotSerializers: [
      'enzyme-to-json/serializer',
   ],
   watchPathIgnorePatterns: ['backstop_data'],
   reporters: ['default', 'jest-html-reporter', 'jest-junit'],
   coverageReporters: ['cobertura', 'html'],
   globals: {
      'ts-jest': {
         tsConfig: '<rootDir>/tsconfig-ts-jest.json',
      },
   },
};

Jest version: 23.6.0 and 24.8.0 OS: Windows 10 pro

I was also having the problem, where --watchAll wasn’t refiring on changes to files. The following Jest config it. Hope it helps you all or someone at least!

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

const config: Config.InitialOptions = {
    globals: {
        "ts-jest": {
            "babelConfig": true,
            "tsconfig": "tsconfig.json"
        }
    },
    rootDir: './',
    transform: {
        "^.+\\.tsx?$": "ts-jest"
    },
    verbose: true,
    testMatch: [
        "/**/*.spec.(ts|js)"
    ],
    moduleFileExtensions: [
        'ts',
        'tsx',
        'js',
        'json',
     ],
    testEnvironment: "node",
    collectCoverage: true,
    cacheDirectory: '<rootDir>/.jest-cache',
    collectCoverageFrom: [
      '**/*.{ts,tsx}',
      '!**/*.config.ts',
      '!**/node_modules/**'
    ],
    coverageReporters: [
      'json',
      'lcov',
    ],
};
export default config;

@github-actions
Copy link

This issue is stale because it has been open for 1 year with no activity. Remove stale label or comment or this will be closed in 30 days.

@github-actions github-actions bot added the Stale label Nov 21, 2022
@github-actions
Copy link

This issue was closed because it has been stalled for 30 days with no activity. Please open a new issue if the issue is still relevant, linking to this one.

@github-actions github-actions bot closed this as not planned Won't fix, can't repro, duplicate, stale Dec 21, 2022
@github-actions
Copy link

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Jan 21, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests