Skip to content

Instantly share code, notes, and snippets.

@Raaghu
Created December 1, 2021 14:02
Show Gist options
  • Save Raaghu/ca8323a414ea0041f3704559fe6d04e4 to your computer and use it in GitHub Desktop.
Save Raaghu/ca8323a414ea0041f3704559fe6d04e4 to your computer and use it in GitHub Desktop.
Run Jest Tests as sequence of steps
/* 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);
}
}
}
@Raaghu
Copy link
Author

Raaghu commented Mar 8, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment