我正在通过npm测试运行Jest测试。Jest默认情况下并行运行测试。是否有办法使测试按顺序运行?
我有一些测试调用依赖于更改当前工作目录的第三方代码。
我正在通过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', () => {}});
}
其他回答
使用串行测试运行器:
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
是的,您还可以以特定的顺序运行所有测试,尽管通常您的测试应该是独立的,所以我强烈警告不要依赖任何特定的顺序。说到这里,可能有一个控制测试顺序的有效案例,所以你可以这样做:
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()在所有测试完成后运行。从本质上讲,它破坏了测试的独立性,应该在非常有限的场景中使用。
这对我来说很有效,确保了模块测试的有序运行:
1)将测试保存在独立的文件中,但没有spec/test的命名。
|__testsToRunSequentially.test.js
|__tests
|__testSuite1.js
|__testSuite2.js
|__index.js
2)测试套件的文件也应该是这样的(testSuite1.js):
export const testSuite1 = () => describe(/*your suite inside*/)
3)将它们导入testtorunsequential .test.js并使用——runInBand运行:
import { testSuite1, testSuite2 } from './tests'
describe('sequentially run tests', () => {
testSuite1()
testSuite2()
})
Jest按照在收集阶段遇到的顺序连续运行所有测试
你可以利用它并创建特殊的测试文件alltests.ordered-test.js:
import './first-test'
import './second-test'
// etc.
并添加一个带有testMatch的笑话配置,它将使用该文件名运行测试。
这将按该顺序加载每个文件,从而以相同的顺序执行它们。
我仍在熟悉Jest,但似乎描述块是同步运行的,而测试块是异步运行的。我在一个外部描述中运行多个描述块,看起来像这样:
describe
describe
test1
test2
describe
test3
在这种情况下,test3直到test2完成才运行,因为test3位于包含test2的描述块之后的描述块中。