jest-wrap icon indicating copy to clipboard operation
jest-wrap copied to clipboard

docs need a note that built-in wrap plugins work with "each", not "all"

Open culshaw opened this issue 6 years ago • 4 comments

When attempting to override a global specified in the jest.config.js we've found it isn't overriden.

We have a set of globals which are basically stubs (in jest.config.js) e.g.

module.exports = {
    globals: {
        YJ: {
            i18n: {
                react: {}
            }
        }
    },
    ...

Then when using jest-wrap to override the i18n key in that global we attempt to do:

const mockYJ = () => ({
    i18n: {
        old_components: {
            form: "1234"
        }
    }
});

wrap()
    .withGlobal("YJ", () => mockYJ)
    .describe("Forms tests", function() {
        beforeAll(function() {
            console.log(YJ.i18n); // { react: {} } 
			// expected { i18n: { old_components: { form: "1234" } } }

But using beforeEach works as expected

wrap()
    .withGlobal("YJ", () => mockYJ)
    .describe("Forms tests", function() {
        beforeEach(function() {
            console.log(YJ.i18n); // { i18n: { old_components: { form: "1234" } } }

culshaw avatar Oct 10 '18 09:10 culshaw

I'm not familiar with the "globals" config you're talking about. Typically you'd use a setup file and mock out the global variable (on the global object) there - not statically in config.

Can you share your entire jest config?

ljharb avatar Oct 11 '18 03:10 ljharb

Ohhhh I get what's happening here.

withGlobal uses beforeEach exclusively - which doesn't run until after all the "beforeAll" callbacks.

I think to make this work properly with beforeAll we'd need to have a version of withGlobal (and thus, withOverrides) that used beforeAll instead of beforeEach. Since "all"-style callbacks are a huge antipattern and lead to test pollution, the ideal course of action here is to migrate from them to "each"-style callbacks. Is that an option?

ljharb avatar Oct 11 '18 03:10 ljharb

Sorry I never replied to this, my github notifications are a space-like vaccuum.

I think just a warning or documentation that it won't work with (after|before)All is all thats needed :)

culshaw avatar May 17 '19 09:05 culshaw

Sounds great - please feel free to make a PR updating the docs! <3

ljharb avatar May 18 '19 07:05 ljharb