ChatGPT解决这个技术问题 Extra ChatGPT

指定 jest 测试文件目录

Am new to unit testing and i wanted only to test files located in a specific directory only

How do i specify that i want tests to run to files only on a specific directory and ignore others

so i have installed jest via npm

  "jest": "^23.6.0",

And specified my test command in package.json via

scripts:{
    "test": "jest --verbose"
 }

The above runs all the files but i want it to run for files in a specific directory eg laratest directory only

How do i proceed


F
FuzzyTree

Add the directory name as an argument

scripts:{
    "test": "jest --verbose ./my-directory"
}

Just to help other jest juniors like me, all your tests files must end int '.test.js' or jest will not find them.
This will also include any subdirectories with the name my-directory.
J
Jason Axelson

Add configuration to your package.json.

"jest": {
  "testMatch": ["**/laratest/**/*.test.js"]
}

https://jestjs.io/docs/configuration#testmatch-arraystring


This can be used for scripts as well: "test:unit": "jest --testMatch '**/src/test/**/?(*.)+(spec|test).[tj]s?(x)'" (I wasn't aware of that).
o
ow3n

Inside ./jest.config.js you can add an array of directories to search

// A list of paths to directories that Jest should use to search for files in
roots: [
    "./",
    "../more-files/"
],

This is what I needed, the configuration snippet to be added to jest.config.js If want to you post this as an answer to a question specifically on config for jest.config.js I'll post a question and send it to you.
Yes, it gives you more control over location. Sure.
K
Kimball Robinson

This article

https://bambielli.com/til/2018-09-09-moving-jest-config-out-of-root/

suggests doing something like this in your config.js file, and I quote the article:

// jest.conf from inside `config/` directory
{
  rootDir: '../',
  globalSetup: {...},
}

E
Erik Erikson

Add the --rootdir option to your command:

jest --verbose --rootDir=laratest

Or in scripts:

scripts:{
    "test": "jest --verbose --rootDir=laratest"
 }

I tried specifying the directory (i.e. jest --verbose ./laratest) in my own project but wasn't seeing the expected result. HTH.


C
Connor Clark

You must be specific in order to avoid running other directories with the same name. For example, this runs only the test in clients:

yarn jest "$PWD/clients"

but this runs tests in any folder named clients:

yarn jest clients
# also: yarn jest ./clients

K
King Friday

Mac solution (not tested on windows)

scripts: {
  ...,
  "test": "export NODE_ENV=development && jest"
}

According to jest docs, the NODE_ENV will be set to test if it is already not set. Thus if you export it... it will pass through to jest.