我正在通过npm测试运行Jest测试。Jest默认情况下并行运行测试。是否有办法使测试按顺序运行?

我有一些测试调用依赖于更改当前工作目录的第三方代码。


当前回答

我仍在熟悉Jest,但似乎描述块是同步运行的,而测试块是异步运行的。我在一个外部描述中运行多个描述块,看起来像这样:

describe
    describe
        test1
        test2

    describe
        test3

在这种情况下,test3直到test2完成才运行,因为test3位于包含test2的描述块之后的描述块中。

其他回答

是的,您还可以以特定的顺序运行所有测试,尽管通常您的测试应该是独立的,所以我强烈警告不要依赖任何特定的顺序。说到这里,可能有一个控制测试顺序的有效案例,所以你可以这样做:

Add --runInBand as an option when running jest, e.g. in package.json. This will run tests in sequence rather than in parallel (asynchronously). Using --runInBand can prevent issues like setup/teardown/cleanup in one set of tests intefering with other tests: "scripts": {"test": "jest --runInBand"} Put all tests into separate folder (e.g. a separate folder under __tests__, named test_suites): __tests__ test_suites test1.js test2.js Configure jest in package.json to ignore this test_suites folder: "jest": { "testPathIgnorePatterns": ["/test_suites"] } Create a new file under __tests__ e.g. tests.js - this is now the only test file that will actually run. In tests.js, require the individual test files in the order that you want to run them: require('./test_suites/test1.js'); require('./test_suites/test2.js');

注意——这将导致测试中的afterAll()在所有测试完成后运行。从本质上讲,它破坏了测试的独立性,应该在非常有限的场景中使用。

以防有人想在包中保留所有的笑话配置。json选项。

runInBand似乎不是一个有效的配置选项。这意味着你可以以下面的设置结束,它似乎不是100%完美的。

"scripts": {
    "test": "jest  --runInBand"
},
...
"jest": {
    "verbose": true,
    "forceExit": true,
    "preset": "ts-jest",
    "testURL": "http://localhost/",
    "testRegex": "\\.test\\.ts$",
    ...
  }
...

但是,你可以像下面这样使用maxWorkers选项添加runInBand:

  "scripts": {
        "test": "jest"
    },
    ...
    "jest": {
        "verbose": true,
        "maxWorkers": 1,
        "forceExit": true,
        "preset": "ts-jest",
        "testURL": "http://localhost/",
        "testRegex": "\\.test\\.ts$",
        ...
      }
    ...

来自Jest文档:

Jest在执行之前执行测试文件中的所有描述处理程序 任何实际的测试。这是另一个建立和的原因 在*和*处理程序之前和之后拆除,而不是在 描述模块。

一旦描述块完成,默认情况下 Jest按顺序连续运行所有测试 遇到在收集阶段,等待每一个完成和被 在继续前进之前整理一下。

看看这个笑话网站给出的例子。

CLI选项有文档记录,也可以通过运行命令jest——help来访问。

你会看到你正在寻找的选项:——runInBand。

我仍在熟悉Jest,但似乎描述块是同步运行的,而测试块是异步运行的。我在一个外部描述中运行多个描述块,看起来像这样:

describe
    describe
        test1
        test2

    describe
        test3

在这种情况下,test3直到test2完成才运行,因为test3位于包含test2的描述块之后的描述块中。