Search code examples
typescriptjestjsts-jest

Jest watch does not build changes to source code


I set my app to watch all tests. It runs the tests each time a file changes, but it doesn't pick up the changes to the source code. If the test succeeded, and the code change breaks the test, the code still succeeds. How can I get it to build the changes before re-running the tests?

jest.config.js

module.exports = {
  testEnvironment: 'node',
  roots: ['<rootDir>'],
  testMatch: ['**/*.test.ts'],
  transform: {
    '^.+\\.tsx?$': 'ts-jest'
  },
};

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2018",
    "module": "commonjs",
    "lib": [
      "es2018"
    ],
    "declaration": true,
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": false,
    "inlineSourceMap": true,
    "inlineSources": true,
    "experimentalDecorators": true,
    "strictPropertyInitialization": false,
    "typeRoots": [
      "./node_modules/@types"
    ]
  },
  "exclude": [
    "node_modules",
    "cdk.out"
  ]
}

package.json

{
  "scripts": {
    "test-watch": "jest --watchAll",
    "ts": "ts-node ./lambda/index.ts"
  },
  "devDependencies": {
    "@types/jest": "^27.5.0",
    "esbuild": "^0.14.48",
    "eslint": "^8.19.0",
    "jest": "^27.5.1",
    "ts-jest": "^27.1.4",
    "ts-node": "^10.7.0",
    "typescript": "~3.9.7"
  },
}

Solution

  • The solution is to run a build watcher and a test-watcher concurrently.

    I.e., run both npm run watch and npm run test-watch

      "scripts": {
        "watch": "tsc -w",
        "test-watch": "jest --watchAll",
    

    The following SO question has multiple solutions on how to run multiple npm scripts at once: How can I run multiple npm scripts in parallel?. One solution from there is:

    If you're using an UNIX-like environment, just use & as the separator:

    "dev": "npm run start-watch & npm run wp-server"
    

    Otherwise if you're interested on a cross-platform solution, you could use npm-run-all module:

    "dev": "npm-run-all --parallel start-watch wp-server"