mochajs / mocha

☕️ simple, flexible, fun javascript test framework for node.js & the browser
https://mochajs.org
MIT License
22.59k stars 3.01k forks source link

Mocha runs old javascript test instead of new typescript test #4981

Closed Almenon closed 9 months ago

Almenon commented 1 year ago

Prerequisites

Description

Mocha runs the test in the compiled javascript file, instead of the test in the typescript file. My understanding of mocha with ts-node is that it should transpile the ts file on the fly, not read the javascript file.

Steps to Reproduce

  1. Clone https://github.com/mochajs/mocha-examples/tree/master/packages/typescript
  2. npm i
  3. Add console.log('foo') to packages\typescript\src\index.ts
  4. Remove outDir in packages\typescript\tsconfig.json
  5. run npm run compile. There will now be a index.js file in src.
  6. run npm test. "foo" is shown
  7. Change foo to fah in index.ts
  8. run npm test

Expected behavior: fah

Actual behavior: foo

Reproduces how often: [What percentage of the time does it reproduce?] 100%

Versions

Additional Information

Might be a issue with ts-node. What's interesting about this is that packages\typescript\.mocharc.json specifies the ts extension only, so I don't know why it's reading the js. Same thing with spec, it specifies just ts.

If you're wondering how this scenario would happen in the real world, I run into it from time to time in https://github.com/almenon/AREPL-backend. I compile the typescript to publish the package but don't always have the compiler running, so the compiled files might not match the typescript files.

Almenon commented 1 year ago

Might be the same bug that https://stackoverflow.com/questions/54807005/mocha-runs-test-from-deleted-spec ran into

JoshuaKGoldberg commented 9 months ago

Mocha can be configured to run on .ts source files using transpilers such as ts-node. But it doesn't do by default. By default, it just reads from .js files.

The mocha-examples/typescript example doesn't use a transpiler. That's why it has a separate compile command to run tsc.

  "scripts": {
    "compile": "tsc --declaration",
    "lint": "tslint --project tsconfig.json",
    "prepublish": "npm run compile",
    "test": "mocha"
  },

The typescript-babel example also doesn't use on-the-fly transpilation.

So this is really a docs / examples request - that we don't have any examples showing on-the-fly transpilation. Filed https://github.com/mochajs/mocha-examples/issues/75 to add examples. Thanks for reporting! 🙌