jest-fast-check
jest-fast-check copied to clipboard
Better `beforeEach` and `afterEach` behavior
It's a bit unfortunate that fast-check has separate lifecycle hooks than jest (e.g. fast-check has asyncBeforeEach
and asyncAfterEach
via configureGlobal
while jest has beforeEach
and afterEach
).
Seems jest doesn't have a way to hook into the functionality, but I wonder if we could include something like this in the package so that calling beforeEach
and afterEach
also sets it up for testProp
.
import { readConfigureGlobal, configureGlobal } from 'fast-check'
const previousBeforeEach = global.beforeEach
const previousAfterEach = global.afterEach
let during = false
global.beforeEach = (fn, ...args) => {
previousBeforeEach(async () => {
if (!during) {
try {
await fn()
} finally {
during = true
}
}
}, ...args)
const { asyncBeforeEach: previousAsyncBeforeEach = () => {} } =
readConfigureGlobal()
configureGlobal({
...readConfigureGlobal(),
async asyncBeforeEach() {
if (!during) {
try {
await previousAsyncBeforeEach()
await fn()
} finally {
during = true
}
}
},
})
}
global.afterEach = (fn, ...args) => {
previousAfterEach(async () => {
if (during) {
try {
await fn()
} finally {
during = false
}
}
}, ...args)
const { asyncAfterEach: previousAsyncAfterEach = () => {} } =
readConfigureGlobal()
configureGlobal({
...readConfigureGlobal(),
async asyncAfterEach() {
if (during) {
try {
await previousAsyncAfterEach()
await fn()
} finally {
during = false
}
}
},
})
}
I've haven't tested this extensively, but I think it ensures that beforeEach
and afterEach
run before and after each "test" without running twice (which is what unfortunately happens normally if you add the same code to jest's beforeEach
and fast-check's asyncBeforeEach
)
Let me know what you think! I'd be happy to make a PR