Rayrun
← Back to Discord Forum

Component testing addInitScript

Hello all

I'm setting up component testing, which I appreciate is experimental, and trying to stub window globals that an internal business library depends on.

I've used the page.addInitScript call and can see it executing in the "actions" panel of the UI before mounting - but when logging out the value of these globals in my source code, the value isn't being set

Is there a more appropriate API for stubbing window globals in component testing?

Here's some contrived example code:

test.beforeEach(async ({ page }) => {
  await page.addInitScript(() => {
    window.$$_INITIAL_STATE_$$ = {
      urls: {
        core: 'https://test-base-url.com',
      },
    };
  });
});

test(`Example`, async ({ mount }) => {
  const component = await mount(<Page />);
  await component
    .getByTestId('page/form')
    .waitFor({ state: 'visible' });
});

And in source:

const internalLib = () => {
  console.log(window.$$_INITIAL_STATE_$$) // undefined
}

This thread is trying to answer question "Is there a more appropriate API for stubbing window globals in component testing than `page.addInitScript`?"

3 replies

I suspect that the initScript isn't being executed as the mount doesn't trigger events that it's subscribed to

My workaround at the moment is to add a script block in the facade page (index.html) but obviously that won't scale well

I've found that using page.evaluate helps get around this issue

Related Discord Threads

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].