Created
December 1, 2021 14:02
-
-
Save Raaghu/ca8323a414ea0041f3704559fe6d04e4 to your computer and use it in GitHub Desktop.
Run Jest Tests as sequence of steps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-disable */ | |
import NodeEnvironment from "jest-environment-node"; | |
/** | |
* Enables to run as steps of a pipeline | |
* | |
* Features | |
* - run all previous tests before running the current test | |
* - Skip all future steps if current step fails | |
* | |
* Conditions | |
* - Works only with one describe block in a file | |
* | |
* Usage | |
* | |
* just add this file as `@jest-environment` code-block | |
* ``` | |
* /** | |
* * @jest-environment ./tests/steps/environment | |
* * / | |
* ``` | |
* | |
*/ | |
export default class StepEnvironment extends NodeEnvironment { | |
async handleTestEvent(event, state) { | |
const skipFutureTests = (testName, state) => { | |
let foundSelectedTest = false; | |
state.currentDescribeBlock.children[0].tests.forEach(test => { | |
if (!foundSelectedTest) { | |
if (test.name == testName) { | |
foundSelectedTest = true; | |
} | |
} else { | |
test.mode = "skip"; | |
} | |
}); | |
}; | |
if ( | |
event.name == "run_describe_start" && | |
event.describeBlock.tests.length > 0 | |
) { | |
const testNamePattern = state.testNamePattern | |
? state.testNamePattern.toString() | |
: "//i"; | |
const testNamePatternStr = testNamePattern.substring( | |
1, | |
testNamePattern.length - 2 | |
); | |
const describeBlockName = event.describeBlock.name; | |
if ( | |
testNamePatternStr.startsWith(describeBlockName) && | |
testNamePatternStr.length > describeBlockName.length | |
) { | |
// testNamePattern starts with this describe name , and has more to it | |
// meaning trying to run a specific test | |
// reset the namePattern only to describeBlock name | |
state.testNamePattern = new RegExp(describeBlockName, "i"); | |
// skip all future tests | |
const testName = testNamePatternStr | |
.substring(describeBlockName.length) | |
.trim(); | |
skipFutureTests(testName, state); | |
} | |
} | |
//skip future tests if current test failed | |
if (event.name == "test_fn_failure") { | |
skipFutureTests(event.test.name, state); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use https://www.npmjs.com/package/jest-environment-steps package to get going easily