An opinionated toast component for React.
feat: add testId prop for individual toast components (#660)
Bahar Hamzehc14bf44a0363
diff --git a/src/index.tsx b/src/index.tsxindex 62b9575..807f000 100644--- a/src/index.tsx+++ b/src/index.tsx@@ -290,6 +290,7 @@ const Toast = (props: ToastProps) => {data-swipe-out={swipeOut}data-swipe-direction={swipeOutDirection}data-expanded={Boolean(expanded || (expandByDefault && mounted))}+ data-testid={toast.testId}style={{'--index': index,diff --git a/src/types.ts b/src/types.tsindex ac0563f..92d033f 100644--- a/src/types.ts+++ b/src/types.ts@@ -86,6 +86,7 @@ export interface ToastT {classNames?: ToastClassnames;descriptionClassName?: string;position?: Position;+ testId?: string;}export function isAction(action: Action | React.ReactNode): action is Action {diff --git a/test/src/app/page.tsx b/test/src/app/page.tsxindex 940f302..1511bb6 100644--- a/test/src/app/page.tsx+++ b/test/src/app/page.tsx@@ -313,6 +313,27 @@ export default function Home({ searchParams }: any) {>With custom ARIA labels</button>+ <button+ data-testid="testid-toast-button"+ className="button"+ onClick={() => toast('Toast with test ID', { testId: 'my-test-toast' })}+ >+ Toast with testId+ </button>+ <button+ data-testid="testid-promise-toast-button"+ className="button"+ onClick={() =>+ toast.promise(promise, {+ loading: 'Loading...',+ success: 'Loaded',+ error: 'Error',+ testId: 'promise-test-toast',+ })+ }+ >+ Promise Toast with testId+ </button>{showAutoClose ? <div data-testid="auto-close-el" /> : null}{showDismiss ? <div data-testid="dismiss-el" /> : null}<Toasterdiff --git a/test/tests/basic.spec.ts b/test/tests/basic.spec.tsindex 87a9655..69eb6e3 100644--- a/test/tests/basic.spec.ts+++ b/test/tests/basic.spec.ts@@ -293,4 +293,24 @@ test.describe('Basic functionality', () => {await expect(page.getByLabel('Notices')).toHaveCount(1);await expect(page.getByLabel('Yeet the notice', { exact: true })).toHaveCount(1);});++ test('toast with testId renders data-testid attribute correctly', async ({ page }) => {+ await page.getByTestId('testid-toast-button').click();+ await expect(page.getByTestId('my-test-toast')).toBeVisible();+ await expect(page.getByTestId('my-test-toast')).toHaveText('Toast with test ID');+ });++ test('toast without testId does not have data-testid attribute', async ({ page }) => {+ await page.getByTestId('default-button').click();+ const toast = page.locator('[data-sonner-toast]');+ await expect(toast).toBeVisible();+ await expect(toast).not.toHaveAttribute('data-testid');+ });++ test('promise toast with testId maintains testId through state changes', async ({ page }) => {+ await page.getByTestId('testid-promise-toast-button').click();+ await expect(page.getByTestId('promise-test-toast')).toBeVisible();+ await expect(page.getByTestId('promise-test-toast')).toHaveText('Loading...');+ await expect(page.getByTestId('promise-test-toast')).toHaveText('Loaded');+ });});