Is there a way to run some tests sequentially with Jest?

后端 未结 4 2032
青春惊慌失措
青春惊慌失措 2021-01-03 23:41

Jest runs your test suite in parallel by default, but there is a flag (--runInBand) that allows you to run the whole suite sequentially (as pointed out here)

4条回答
  •  时光取名叫无心
    2021-01-04 00:28

    This was a bit of a lift, but I think it's worth posting my final config. I had this same problem and I extended Joachim Lous' and Fishball's answers to get to a satisfactory result. Here's my final setup:

    An abbreviated directory listing of my project:

    ├── src
    │   ├── index.ts
    │   ├── Io.ts
    │   ├── Modules
    │   │   └── index.ts
    │   └── .....
    └── tests
        ├── EndToEnd
        │   ├── Fixtures.ts
        │   ├── Mq.spec.ts
        │   ├── LegalEntities.spec.ts
        │   └── Utils.ts
        └── UnitTests
            ├── LegalEntities.spec.ts
            ├── Assets.spec.ts
            └── Utils.ts
    

    My (abbreviated) package.json file with my jest configs in it:

    {
      "name": "my-project",
      "scripts": {
        "build": "scripts/build",
        "check": "tsc --noEmit",
        "test": "jest"
      },
      "....": "....",
      "jest": {
        "projects": [
          {
            "displayName": "unit-tests",
            "testEnvironment": "node",
            "verbose": true,
            "testMatch": [
              "/tests/**/*.spec.ts",
              "!**/EndToEnd/**/*.spec.ts"
            ],
            "transform": {
              "^.+\\.tsx?$": "ts-jest"
            }
          },
          {
            "displayName": "e2e-tests",
            "testEnvironment": "node",
            "verbose": true,
            "maxWorkers": 1,
            "testMatch": [
              "/tests/EndToEnd/**/*.spec.ts"   
            ],
            "transform": {
              "^.+\\.tsx?$": "ts-jest"
            }
          }
        ]
      }
    }
    

    Things to note:

    • When using the projects key in jest, I had to move all config into the individual project blocks. Using project config was mutually-exclusive with using global config.
    • I did not use the runner directive as mentioned in other answers. Instead I used the maxWorkers option to limit execution to 1 worker (i.e., inherently serial). This meant I didn't have to use more dependencies.
    • For some reason the negation syntax was finicky with my unit tests. I wanted to specify unit tests as all tests that were NOT in the EndToEnd directory, and it took me a few tried to get jest to do this correctly.

    Thanks to everyone else for the viable starting point. Hope this helps others!

提交回复
热议问题