Skip to content

Testing ​

React parts are tested with Jest and Testing Library, run npm test.

The configuration is shared and lives in the base theme (jest.base.cjs): a subtheme has no jest.config.cjs, no Babel config and no test dependencies. npm test runs frame test, extra arguments go to Jest: npm test -- --watch, npm test -- -u.

What the shared config does
jsdom environmentresolved from the base theme
Babel (preset-env, preset-react classic)presets resolved from the base theme, so no .babelrc is needed
Components/... aliasmaps to <theme>/components
CSS/SCSS importsmocked
One Reactreact / react-dom always resolve to the base theme copy, even if a dependency (rsuite) installed another
@testing-library/*importable from the base theme location
setup filejest-dom matchers, global React, stubs for Drupal.t and drupalSettings, matchMedia

To override something add a jest.config.cjs to the theme, it is used instead: module.exports = require('<base theme>/jest.base.cjs')(__dirname, { testPathIgnorePatterns: [...] }). The base theme's own tests (src/__tests__) cover apiClient and executeWhenVisible.

Example ​

Components rely on globals that Drupal provides (Drupal, and apiClient for a component that loads data), so stub them in beforeEach. This is cut down from the test of the pricing-table component:

jsx
import { PricingTable } from '../PricingTable';
import { render, screen, waitFor, fireEvent } from '@testing-library/react';

const plans = [
  { name: 'Taster', monthly: 29, yearly: 24 },
  { name: 'Cook', monthly: 79, yearly: 63.5, highlight: true, badge: 'Popular' },
];

beforeEach(() => {
  window.Drupal = {
    t: (s, args = {}) => Object.entries(args).reduce((r, [k, v]) => r.replace(k, v), s),
  };
  document.documentElement.lang = 'en';
});

it('switches between monthly and yearly prices', () => {
  render(<PricingTable currency="EUR" plans={plans} />);
  expect(screen.getByText('€29')).toBeTruthy();
  fireEvent.click(screen.getByLabelText(/Yearly/));
  expect(screen.getByText('€24')).toBeTruthy();
});

For a component that loads data, replace apiClient in beforeEach and check the call:

jsx
window.apiClient = jest.fn(() => Promise.resolve({ rows: [] }));
global.apiClient = window.apiClient;
// ...
await waitFor(() => expect(apiClient).toHaveBeenLastCalledWith('/api/recipes', { difficulty: 'hard' }));

Test the React component (PricingTable.jsx), not index.jsx: the behavior wrapper only wires Drupal to React.

What is not covered ​

  • Drupal-side rendering (SDC props validation, library attachment) needs a running site or core's ComponentKernelTestBase.