Run only ONE test with Jest

2020-02-26 02:28发布

问题:

Very simple, I want to run just one test with Jest.

I put it.only or describe.only but it still runs a whole lot of tests. I think it runs all the tests since my last commit, but it shouldn't have this behavior with the only flag explicitly set, right?

What causes this behavior and how to run a single test?

回答1:

Jest parallelizes test runs and it doesn't know upfront which tests it should run and which it shouldn't run. This means when you use "fit", it will only run one test in that file but still run all other test files in your project.

fit, fdescribe and it.only, describe.only have the same purpose, skip other tests, run only me.

Source: https://github.com/facebook/jest/issues/698#issuecomment-177673281


Use jest filtering mechanism, when you run your tests like

jest --config=jest.config.json --watch

You can filter tests by a testname or filename, just follow instructions in the terminal

Press p, then type a filename

Then you can use describe.only and it.only which will skip all other tests from filtered, tested file.



回答2:

it.only and describe.only work only for the module they are in. If you are having problems to filter tests in multiple files, you can use jest -t name-of-spec, filtering tests that match the spec name (match against the name in describe or test).
Source: https://facebook.github.io/jest/docs/en/cli.html

For example, I focus the test which I'm currently writing like this (with the test script in the package.json):
npm test -- -t "test foo"



回答3:

For me it works if I use 2 params like this:

yarn test --watch -f "src/...fullpath.../reducer.spec.js" -t "Name of the test"

--watch: is optional

-f: will do filtering of your files, so if you have a lot of tests with same name, specify fullpath to exact file

-t: works with 'describe' name or 'it' name of your test



回答4:

it's like this:

jest sometest.test.js -t "some expression to match a describe or a test"

it will test all files with the name sometest.test.js and matching based on -t option, if you only want to test a specific file you can do this:

jest src/user/.../sometest.test.js