Jest: Shared Async Code Between Test Blocks
I have some test code like this: test('Test', async () => { const someData = await setup() const actual = myFunc(someData.x) expect(actual.a).toEqual(someData.y) expect(
Solution 1:
It's correct that describe
callback function isn't supposed to be asynchronous. It synchronously defines tests for a suite, any asynchronous operations in its scope will be discarded.
Previously Jasmine and Jest allowed to access common test context with regular functions and this
. This feature was deprecated in Jest; common variables need to be user-defined.
Shared code can be moved into helper function that internally uses beforeAll
, beforeEach
, etc:
constsetupWithTestContext = (testContext = {}) => {
beforeAll(async () => {
const setupData = awaitsetup();
Object.assign(testContext, setupData);
});
return testContext; // sets up a new one or returns an existing
});
constanotherSetupWithTestContext = (testContext = {}) => {
beforeEach(() => {
testContext.foo = 0;
});
return testContext;
});
...
describe('Some group of tests', async () => {
const sharedTestData = setupTestContext();
// or// const sharedTestData = {}; setupTestContext(sharedTestData);anotherSetupWithTestContext(sharedTestData);
test('Test1', async () => {
// context is filled with data at this pointconst actual = myFunc(sharedTestData.x)
...
}
...
})
Post a Comment for "Jest: Shared Async Code Between Test Blocks"