如何在React Testing Library中单独测试指定模块(Jest环境)
Got it, let's get this sorted so you're only running the specific Module.spec.js file you care about, instead of every matching file in your project. Here are the most straightforward solutions:
1. Use the full relative path to your target file
Instead of just passing Module to the test command, specify the complete relative path to your component's test file. This tells Jest exactly which file to run, no more matching duplicates.
For example, if your target file lives at src/components/CheckoutModule/Module.spec.js, your command would look like:
env DEBUG_PRINT_LIMIT=50000 npm test -- ./src/components/CheckoutModule/Module.spec.js --watch
2. Use a precise partial path (if you're already in the component directory)
If you're already navigated to the component's folder (e.g., you're in src/components/CheckoutModule/), you can use the local path to the file instead of the full project path. This avoids global searches for matching filenames:
env DEBUG_PRINT_LIMIT=50000 npm test -- ./Module.spec.js --watch
The ./ here is key—it tells Jest to look only in your current working directory, not the entire project.
3. Add a directory prefix to narrow matches
If you don't want to type the full path, you can add the parent directory of your target file to the command. This filters out other Module.spec.js files in different directories. For example:
env DEBUG_PRINT_LIMIT=50000 npm test -- CheckoutModule/Module.spec.js --watch
Why your original command wasn't working
Jest's default behavior is to search your entire project for files matching the pattern you pass. When you only use Module, it finds every Module.spec.js file across all directories. By adding a specific path (full or partial), you restrict the search to exactly the file you want.
Bonus: Make it easier with a npm script
If you do this often, you can add a custom script to your package.json to save typing:
{ "scripts": { "test:single": "env DEBUG_PRINT_LIMIT=50000 npm test -- $1 --watch" } }
Then run your specific test with:
npm run test:single ./src/components/CheckoutModule/Module.spec.js
内容的提问来源于stack exchange,提问作者Bablu Ahmed

