Skip to content

[Feature request]: Change globals before rendering story #535

@fredcido

Description

@fredcido

Is your feature request related to a problem? Please describe.

Hey all,

I've been using a decorator + global types to support locales on our stories:

// preview.tsx

export const globalTypes = {
  locale: {
    name: 'Locale',
    description: 'Internationalization locale',
    toolbar: {
      icon: 'globe',
      items: languages,
    },
  },
}

In the stories we allow to define supported languages for visual regression tests:

// my.stories.tsx

const Story: Meta<typeof PageContent> = {
  component: PageContent,
  title: 'Page Layouts/Layouts/Page',
  parameters: {
    i18n: {
      namespace: 'pricing',
      visualTests: ['en', 'es', 'fr'],
    },
  },
}

What I am trying to achieve is to use one of the existing hooks from test runners to set the globals before rendering the story based on these configured parameters, the solution I've found out so far was to read current page URL and set the globals using query parameter, but that brings a lot of overhead since for each language the page needs to be reloaded:

// test-runner.ts

const config: TestRunnerConfig = {
  tags: {
    include: ['visual-tests'],
  },
  setup: () => {
    expect.extend({toMatchImageSnapshot})
  },
  preRender: async (page, context) => {
    const pageContext = await getStoryContext(page, context)
    const languages = pageContext.parameters.i18n.visualTests
    for (const lang of languages) {
      const newUrl = new URL(page.url())
      newUrl.searchParams.set('globals', `locale:${lang}`)
     // Refreshing the whole page on every language doesn't seem a good idea
      await page.goto(newUrl.toString())

      const image = await page.screenshot({
        fullPage: true,
        animations: 'disabled',
      })

      expect(image).toMatchImageSnapshot()
    }
  },
}

Describe the solution you'd like

What would be the best way to set these globals for the story before it's rendered based on these parameters?
Not to mention we are going to have multiple breakpoints too, which could exponentially increase test timeouts.

Describe alternatives you've considered

No response

Are you able to assist to bring the feature to reality?

no

Additional context

No response

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