Back to Storybook

Shadow Dom Testing Library In Preview

docs/_snippets/shadow-dom-testing-library-in-preview.md

10.3.62.2 KB
Original Source
ts
import type { Preview } from '@storybook/web-components-vite';

import { within as withinShadow } from 'shadow-dom-testing-library';

const preview: Preview = {
  // ๐Ÿ‘‡ Augment the canvas with the shadow DOM queries
  beforeEach({ canvasElement, canvas }) {
    Object.assign(canvas, { ...withinShadow(canvasElement) });
  },
  // ...
};

// ๐Ÿ‘‡ Extend TypeScript types for safety
export type ShadowQueries = ReturnType<typeof withinShadow>;

// Since [email protected]
declare module 'storybook/internal/csf' {
  interface Canvas extends ShadowQueries {}
}

export default preview;
js
import { within as withinShadow } from 'shadow-dom-testing-library';

export default {
  // ๐Ÿ‘‡ Augment the canvas with the shadow DOM queries
  beforeEach({ canvasElement, canvas }) {
    Object.assign(canvas, { ...withinShadow(canvasElement) });
  },
  // ...
};
ts
import { definePreview } from '@storybook/web-components-vite';

import { within as withinShadow } from 'shadow-dom-testing-library';

// ๐Ÿ‘‡ Extend TypeScript types for safety
export type ShadowQueries = ReturnType<typeof withinShadow>;

// Since [email protected]
declare module 'storybook/internal/csf' {
  interface Canvas extends ShadowQueries {}
}

export default definePreview({
  // ๐Ÿ‘‡ Augment the canvas with the shadow DOM queries
  beforeEach({ canvasElement, canvas }) {
    Object.assign(canvas, { ...withinShadow(canvasElement) });
  },
  // ...
});
<!-- JS snippets still needed while providing both CSF 3 & Next -->
js
import { definePreview } from '@storybook/web-components-vite';

import { within as withinShadow } from 'shadow-dom-testing-library';

export default definePreview({
  // ๐Ÿ‘‡ Augment the canvas with the shadow DOM queries
  beforeEach({ canvasElement, canvas }) {
    Object.assign(canvas, { ...withinShadow(canvasElement) });
  },
  // ...
});