Search code examples
node.jstypescriptglobnode-test-runner

How to recursively match Typescript test files with NodeJS native testrunner


NodeJS recently added a native test runner

I can successfully get it to run typescript tests with ts-node or tsx

  • node --loader ts-node/esm --test **/*.test.ts
  • node --loader tsx --test **/*.test.ts

But one major drawback is the glob pattern (**/*.test.ts) is not working as expected. It is only finding *.test.ts files down one directory, and is not recursively finding test files in nested directories. I think the problem is that node isn't treating ** as a recursive glob pattern.

edit: It looks like the testrunner uses this glob library which may not support that syntax...

  • src/bar.test.ts is found
  • src/foo/bar.test.ts is not found

I'd like to be able to put *.test.ts files anywhere in my app and have the test script execute them. Is there any way to accomplish this?

.
├── package.json
├── src
│   ├── app
│   │   ├── dir
│   │   │   └── more-nested.test.ts
│   │   └── nested-example.test.ts
│   └── example.test.ts
└── tsconfig.json

Solution

  • ** is known as globstar and is not available on every system.

    First possible solution is to use find from the root folder to get a list of files matching a specified pattern (it will look in every subfolder) and then run node --loader tsx --test for every found file:

    find . -name "*.test.ts" -exec node --loader tsx --test {} ';'

    Another possible solution (reference: https://github.com/nodejs/help/issues/3902#issuecomment-1307124174) is to create a custom script that finds all files and subdirectories using glob package and then run tests invoking node --loader tsx --test ... with child_process.

    Check also this: Why can't ** be used (for recursive globbing) in a npm package.json script, if it works in 'npm shell'?