cloudflare / miniflare-typescript-esbuild-jest

Example project using Miniflare, TypeScript, esbuild and Jest
86 stars 21 forks source link

Jest `--watch` doesn't pick up changes to DO definitions #7

Open geelen opened 2 years ago

geelen commented 2 years ago

Hey, this project was a huge help in understanding how to get set up with a miniflare Jest setup with TS and DOs and everything, thanks for that!

One thing I hit was that I can't live-reload the DO definitions. I use that a lot for development, and it works for the other pieces of the worker, just not the DO.

To reproduce:

git clone git@github.com:mrbbot/miniflare-typescript-esbuild-jest.git
cd miniflare-typescript-esbuild-jest
npm install
npm run test -- --watchAll

To see it working, go change a line like https://github.com/mrbbot/miniflare-typescript-esbuild-jest/blob/fcd5f82ed7a864650902adb490d6d5b8b8f6e33f/src/index.ts#L7 and see the tests immediately fail.

For the DO, changing a line like https://github.com/mrbbot/miniflare-typescript-esbuild-jest/blob/fcd5f82ed7a864650902adb490d6d5b8b8f6e33f/src/counter.ts#L12 does break the test, but requires you to restart npm run test -- --watchAll to see the failure happen.

My workaround is to rerun the whole suite on each change using chokidar-cli, which works but will be slow once I have a decent-sized app:

  "scripts": {
    "build": "node build.js",
    "dev": "miniflare --live-reload --debug",
    "test": "npm run build && node --experimental-vm-modules node_modules/jest/bin/jest.js",
    "types:check": "tsc && tsc -p test/tsconfig.json",
+   "test:watch": "chokidar 'src/**' 'test/**' -c 'npm run test' --initial"
  },
geelen commented 2 years ago

Found another workaround:

    "test": "npm run build && npm run test:all",
    "test:all": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
    "test:watch": "concurrently -k -c red,green 'npm run build -- --watch' 'npm run test:all -- --watchAll'",

Or if you're using yarn:

    "test": "yarn build && yarn test:all",
    "test:all": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
    "test:watch": "concurrently -k -c red,green 'yarn build --watch' 'yarn test:all --watchAll'",

Note that --watchAll is important, we're defeating Jest's understanding of which files have changed so we have to rerun the whole suite.

await build({
  // ...
  watch: process.argv.includes('--watch')
    ? {
        onRebuild(error, result) {
          if (error) return console.error('watch build failed:', error)
          const now = new Date()
          fs.utimes('test/index.spec.ts', now, now, () => {
            console.log('Rebuilt dist/index.js. Notified Jest.')
          })
        },
      }
    : false,

That call to utimes is enough for Jest to trigger a rebuild, so this works!