Skip to contentPorsche Design System
You are currently viewing an earlier release of the Porsche Design System.Switch to the latest Porsche Design System documentation.
SearchGitHub repository of Porsche Design SystemOpen settings sidebar
Next.js Table of Contents Test the application Jest uses jsdom and supports ShadowDOM since Version 12.2.0. However, it doesn't support JavaScript modules as described in this issue. Also, it doesn't support CSSStyleSheet.replace(), Intersection Observer, Element.prototype.scrollTo and others. As a workaround we provide a polyfill as part of the @porsche-design-system/components-react package. The polyfill requires jsdom v30 or higher. On older versions it throws an explicit error on import. To apply the polyfill, simply import it in your setupTest.{js|ts} file. Note: If your test includes Porsche Design System components, make sure to wrap the component you want to test with a PorscheDesignSystemProvider in order to avoid exceptions. Certain modern browser APIs are not supported in the jsdom environment. See Unsupported APIs for more information. Setup file
// setupTest.{js|ts}

import '@porsche-design-system/components-react/jsdom-polyfill';
Example component
// SingleComponent.tsx

import { useCallback, useState } from 'react';
import { PTabsBar, type TabsBarUpdateEventDetail } from '@porsche-design-system/components-react/ssr';

export const SingleComponent = (): JSX.Element => {
  const [activeTab, setActiveTab] = useState(0);
  const onUpdate = useCallback((e: CustomEvent<TabsBarUpdateEventDetail>) => {
    setActiveTab(e.detail.activeTabIndex);
  }, []);

  return (
    <>
      <PTabsBar activeTabIndex={activeTab} onUpdate={onUpdate} data-testid="host">
        <button data-testid="button1">Some label</button>
        <button data-testid="button2">Some label</button>
        <button data-testid="button3">Some label</button>
      </PTabsBar>
      <div data-testid="debug">{`Active Tab: ${activeTab + 1}`}</div>
    </>
  );
};
Test example component
// SingleComponent.test.tsx

import { PorscheDesignSystemProvider, componentsReady } from '@porsche-design-system/components-react/ssr';
import { render } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

test('renders Tabs Bar from Porsche Design System and uses its events', async () => {
  const { getByTestId } = render(
    <PorscheDesignSystemProvider>
      {' '}
      {/* required for the component to work */}
      <SingleComponent />
    </PorscheDesignSystemProvider>
  );

  await componentsReady(); // we need to make sure Porsche Design System components are initialized

  const debug = getByTestId('debug');
  const button1 = getByTestId('button1');
  const button2 = getByTestId('button2');
  const button3 = getByTestId('button3');

  expect(debug.innerHTML).toBe('Active Tab: 1');

  await userEvent.click(button2);
  expect(debug.innerHTML).toBe('Active Tab: 2');

  await userEvent.click(button3);
  expect(debug.innerHTML).toBe('Active Tab: 3');

  await userEvent.click(button1);
  expect(debug.innerHTML).toBe('Active Tab: 1');
});
Hints about PorscheDesignSystemProvider It might be rather redundant to wrap every single test with PorscheDesignSystemProvider. Therefore, we offer the following advice. Custom helper To reduce repetitive code you can write a custom helper function that wraps a component in PorscheDesignSystemProvider and calls the render function of @testing-library/react:
// helper.tsx

import { render, RenderResult } from '@testing-library/react';
import { PorscheDesignSystemProvider } from '@porsche-design-system/components-react/ssr';

export const renderWithProvider = (component: JSX.Element): RenderResult => {
  return render(<PorscheDesignSystemProvider>{component}</PorscheDesignSystemProvider>);
};
Disabling the validation of PorscheDesignSystemProvider Alternatively we provide a utility function skipCheckForPorscheDesignSystemProviderDuringTests() that can be used within your tests. It only takes effect during testing since it relies on process.env.NODE_ENV === 'test'. You can apply it globally on every test by calling it once in your test setup:
// setupTest.{js|ts}
import { skipCheckForPorscheDesignSystemProviderDuringTests } from '@porsche-design-system/components-react/ssr';

skipCheckForPorscheDesignSystemProviderDuringTests();
If you don't want to have multiple test setups or prefer a more local approach you can use it within your test:
// SomeComponent.test.tsx
import { skipCheckForPorscheDesignSystemProviderDuringTests } from '@porsche-design-system/components-react/ssr';

describe('SomeComponent', () => {
  beforeEach(() => {
    // either like this
    skipCheckForPorscheDesignSystemProviderDuringTests();
  });

  it('should work', () => {
    // or like this
    skipCheckForPorscheDesignSystemProviderDuringTests();

    // ...
  });
});
Disabling CDN requests from Porsche Design System and components We provide a utility function skipPorscheDesignSystemCDNRequestsDuringTests() that can be used within your tests when you use the @porsche-design-system/components-react/jsdom-polyfill in your setup. It will suppress all CDN request of the Porsche Design System. You can apply it globally on every test by calling it once in your test setup:
// setupTest.{js|ts}
import { skipPorscheDesignSystemCDNRequestsDuringTests } from '@porsche-design-system/components-react/ssr';

skipPorscheDesignSystemCDNRequestsDuringTests();
If you don't want to have multiple test setups or prefer a more local approach you can use it within your test:
// SomeComponent.test.tsx
import { skipPorscheDesignSystemCDNRequestsDuringTests } from '@porsche-design-system/components-react/ssr';

describe('SomeComponent', () => {
  beforeEach(() => {
    // either like this
    skipPorscheDesignSystemCDNRequestsDuringTests();
  });

  it('should work', () => {
    // or like this
    skipPorscheDesignSystemCDNRequestsDuringTests();

    // ...
  });
});
Additional information when using @testing-library/react Form Submission If you try to submit a form via button click you will encounter issues with @testing-library/react and jsdom. It is simply not provided (see Github Issue 755 and Github Issue 1937). If you have to test a form submit use Simulate.
import { Simulate } from 'react-dom/test-utils';

const button = getByText('SomePorscheDesignSystemButton');

Simulate.submit('button');
Queries Porsche Design System components render their markup inside Shadow DOM. Standard Testing Library queries such as getByRole only search light DOM, so they never reach those elements and find nothing. Therefore the testing sub-package provides a Shadow counterpart for every Testing Library query. These search light DOM and Shadow DOM, including nested Shadow DOM. All 48 available queries: AltText: getByShadowAltText, getAllByShadowAltText, queryByShadowAltText, queryAllByShadowAltText, findByShadowAltText, findAllByShadowAltText DisplayValue: getByShadowDisplayValue, getAllByShadowDisplayValue, queryByShadowDisplayValue, queryAllByShadowDisplayValue, findByShadowDisplayValue, findAllByShadowDisplayValue LabelText: getByShadowLabelText, getAllByShadowLabelText, queryByShadowLabelText, queryAllByShadowLabelText, findByShadowLabelText, findAllByShadowLabelText PlaceholderText: getByShadowPlaceholderText, getAllByShadowPlaceholderText, queryByShadowPlaceholderText, queryAllByShadowPlaceholderText, findByShadowPlaceholderText, findAllByShadowPlaceholderText Role: getByShadowRole, getAllByShadowRole, queryByShadowRole, queryAllByShadowRole, findByShadowRole, findAllByShadowRole TestId: getByShadowTestId, getAllByShadowTestId, queryByShadowTestId, queryAllByShadowTestId, findByShadowTestId, findAllByShadowTestId Text: getByShadowText, getAllByShadowText, queryByShadowText, queryAllByShadowText, findByShadowText, findAllByShadowText Title: getByShadowTitle, getAllByShadowTitle, queryByShadowTitle, queryAllByShadowTitle, findByShadowTitle, findAllByShadowTitle
import { screen } from '@porsche-design-system/components-react/testing';

it('should work for PInputText', async () => {
  render(<PInputText label="Some label" name="some-name" />);
  await componentsReady();

  const input = screen.getByShadowRole('textbox', { name: 'Some label' });

  expect(input).toBe(document.querySelector('p-input-text').shadowRoot.querySelector('input'));
});
Also exported: screen (every query above, bound to document), within, deepQuerySelector, deepQuerySelectorAll, getAllElementsAndShadowRoots, debug, logShadowDOM, prettyShadowDOM, logRoles, configure and getConfig. These queries need a DOM to search. Importing the testing sub-package where no DOM is available throws an error. Porsche Design System queries Before the queries above were available we shipped three helpers of our own. They are still exported and still supported, so existing tests keep working. For new tests prefer the shadow queries above, which cover every query family rather than three. OursEquivalent abovegetByRoleShadowedgetByShadowRolegetByLabelTextShadowedgetByShadowLabelTextgetByTextShadowedgetByShadowText Unlike the shadow queries, these three take an optional container as their first argument and fall back to the whole document when it is omitted.
import { getByRoleShadowed } from '@porsche-design-system/components-react/testing';

it('should work for PButton', async () => {
  render(<PButton>Button</PButton>);
  await componentsReady();

  expect(getByRoleShadowed('button')).toBeInTheDocument();
});
We also provide test examples in our sample integration project. Unsupported APIs Certain modern browser APIs are not supported in the jsdom environment. Dialog API Affected Components: p-modal, p-flyout, p-sheet, p-drilldown Due to the lack of native support in jsdom, the Dialog API needs to be either manually polyfilled or mocked. You can use the available dialog-polyfill package or create a custom mock implementation. Example mock:
HTMLDialogElement.prototype.show = jest.fn();
HTMLDialogElement.prototype.showModal = jest.fn(function (this: HTMLDialogElement) {
  this.setAttribute('open', '');
});
HTMLDialogElement.prototype.close = jest.fn(function (this: HTMLDialogElement) {
  this.removeAttribute('open');
});
Element Internals API Affected Components: p-button, p-button-pure, p-checkbox, p-input-date, p-input-email, p-input-month, p-input-number, p-input-password, p-input-search, p-input-tel, p-input-text, p-input-time, p-input-url, p-input-week, p-multi-select, p-pin-code, p-radio-group, p-segmented-control, p-select, p-textarea Current polyfills for the Element Internals API are incompatible with Stencil. Therefore, the API must be mocked within the test setup. Example mock:
HTMLElement.prototype.attachInternals = jest.fn(
  () =>
    ({
      setFormValue: jest.fn(),
      setValidity: jest.fn(),
    }) as ElementInternals
);
animate API Affected Components: p-tabs-bar, p-tabs, p-drilldown The API must be mocked within the test setup. Example mock:
Element.prototype.animate = vi.fn(
  () =>
    ({
      onfinish: null,
      cancel: vi.fn(),
      finish: vi.fn(),
    }) as unknown as Animation
);
Global settingsColor SchemeAll color tokens use the light-dark() CSS function. Set the theme via the CSS color-scheme property: light for light mode, dark for dark mode, or light dark to follow the user's system preference.LightDarkLight DarkDirectionThe dir global attribute in HTML changes the direction of text and other content within an element. It's most often used on the <html> tag to set the entire page's direction, which is crucial for supporting languages that are written from right to left (RTL), such as Arabic and Hebrew. For example, using <html dir="rtl"> makes the entire page display from right to left, adjusting the layout and text flow accordingly.LTR (left-to-right)RTL (right-to-left)Text ZoomTo ensure accessibility and comply with WCAG 2.2 AA standards, it is mandatory for web content to support text resizing up to at least 200% without loss of content or functionality. Using relative units like rem is a best practice for achieving this, as they allow the text to scale uniformly based on the user's browser settings.100%130%150%200%