Skip to content

Instantly share code, notes, and snippets.

@danhab99
Last active October 29, 2021 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danhab99/36a5f56e48096916e0684c034e094fd3 to your computer and use it in GitHub Desktop.
Save danhab99/36a5f56e48096916e0684c034e094fd3 to your computer and use it in GitHub Desktop.
Cannot pass state from jest wrapper to sub tests
const EXAMPLE_KEY = "example key";
const describeWrapper = (label, opts, tests) => {
describe(label, () => {
var State = undefined;
beforeAll(async () => {
// acquiring the state irl has to be done asynchronously
State = EXAMPLE_KEY;
})
afterAll(async () => {
State = ""
})
if (opts.passAsFunction) {
test(() => State)
}
else {
test(State)
}
})
}
describeWrapper("An example test passing the state as a function", { passAsFunction: true }, (state) => {
var S;
beforeAll(async () => {
S = state()
})
test("State is defined", () => {
expect(S).toBeDefined()
expect(S).toBe(EXAMPLE_KEY)
})
})
describeWrapper("An example test passing the state directly", { passAsFunction: false }, (State) => {
test("State is defined", () => {
expect(State).toBeDefined()
expect(State).toBe(EXAMPLE_KEY)
})
})
/**
Expected output
$ npx jest demo.test.js
FAIL ./demo.test.js
● Test suite failed to run
Invalid first argument, () => State. It must be a string.
15 |
16 | if (opts.passAsFunction) {
> 17 | test(() => State)
| ^
18 | }
19 | else {
20 | test(state)
at demo.test.js:17:7
at describeWrapper (demo.test.js:4:3)
at Object.<anonymous> (demo.test.js:25:1)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 0.138 s
Ran all test suites matching /demo.test.js/i.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment