Skip to content

Allow to share global state between tests from globalSetup #7184

Open
@dbartholomae

Description

@dbartholomae

🚀 Feature Proposal

Add a global property to the this of globalSetup and globalTeardown async functions that can be used to set global variables that can be accessed in all tests via global. The same global is shared across all tests.

Motivation

While jest was in the beginning used only for frontend testing, it has moved in the direction of becoming a general test framework. Especially for backend integration tests there is a tradeoff between test speed and departmentalization: Starting up a new backend instance for each individual test usually isn't feasible. Therefore most other test frameworks like mocha or jasmine provide possibilities to share state between tests, e. g. the backend instance. Usage examples include mocking http requests via nock.

Example

Let's assume an integration test that tests backend and database integration. The setup could look like this:

const backend = require('backend')

async function setupApp () {
  await new Promise((resolve, reject) => {
    backend.start().then((instance) => {
      this.global.backend = instance
    })
  })
}

module.exports = setupApp

And using the global could be done like this:

const request = require('supertest')
test('should call out to that fancy other api', () => {
  request(jest.globals.backend.url)
    .post('/some-endpoint')
    expect(200)
})

Pitch

As far as I know this change currently cannot be implemented outside of the main jest framework. Closest is an environment, but environments are sandboxed and do not share global state.

Open questions

How to best implement it?

I don't know the jest code well enough to have an idea how to best implement this. It might e. g. be easier to make the global available via global, or even jest.getGlobals().

Can we prevent misuse?

Sharing state between tests can lead to sideffects and random test breakage. One possible solution would be to make the jest.globals read-only, but I am not sure whether this is feasible without massively reducing which kind of objects can be stored.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions