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

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


当前回答

摘自https://github.com/facebook/jest/issues/6194#issuecomment-419837314

test.spec.js

import { signuptests } from './signup'
import { logintests } from './login'

describe('Signup', signuptests)
describe('Login', logintests)

signup.js

export const signuptests = () => {
     it('Should have login elements', () => {});
     it('Should Signup', () => {}});
}

login.js

export const logintests = () => {
    it('Should Login', () => {}});
}

其他回答

以防有人想在包中保留所有的笑话配置。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按顺序连续运行所有测试 遇到在收集阶段,等待每一个完成和被 在继续前进之前整理一下。

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

使用串行测试运行器:

npm install jest-serial-runner --save-dev

设置jest来使用它,例如在jest.config.js中:

module.exports = {
   ...,
   runner: 'jest-serial-runner'
};

您可以使用项目特性将其仅应用于测试的一个子集。看到https://jestjs.io/docs/en/configuration projects-arraystring——projectconfig

Jest按照在收集阶段遇到的顺序连续运行所有测试

你可以利用它并创建特殊的测试文件alltests.ordered-test.js:

import './first-test'
import './second-test'
// etc.

并添加一个带有testMatch的笑话配置,它将使用该文件名运行测试。

这将按该顺序加载每个文件,从而以相同的顺序执行它们。

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

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()在所有测试完成后运行。从本质上讲,它破坏了测试的独立性,应该在非常有限的场景中使用。