Evanss
Evanss

Reputation: 23142

Global beforeAll in Jest?

I need to simulate different window sizes in my tests using React Testing Library and Jest.

Currently I'm having to have this beforeAll in every test file:

import matchMediaPolyfill from 'mq-polyfill';

beforeAll(() => {
  matchMediaPolyfill(window)
  window.resizeTo = function resizeTo(width, height) {
    Object.assign(this, {
      innerWidth: width,
      innerHeight: height,
      outerWidth: width,
      outerHeight: height,
    }).dispatchEvent(new this.Event('resize'))
  }
})

Which I use like so:

it('does something at small screen sizes', async () => {
  window.resizeTo(320, 800);
  // actual test here

Can I have a global beforeAll that will apply to every test file in my project?

The docs mention globalsetup: https://jestjs.io/docs/en/configuration#globalsetup-string

However it errors as it doenst recognise the beforeAll function. I seemed to me that that option is meant for setting up an environment but not adding something to the test files?

Upvotes: 11

Views: 17775

Answers (1)

Estus Flask
Estus Flask

Reputation: 222979

globalSetup runs in another process and cannot access beforeAll or other variables from test scope. It's meant for initializations made before any test is started, e.g. setting up a server, like the documentation shows.

It's setupFiles that runs in test process. beforeAll should be executed after Jest environment is initialized, so it should be moved to setupFilesAfterEnv.

Upvotes: 8

Related Questions