import { describe, expect, it, vi } from 'vitest'; import { render, screen } from '@testing-library/svelte'; import userEvent from '@testing-library/user-event'; import hljs from 'highlight.js'; import CodeSnippet from '../code-snippet.svelte'; import CaptionedCodeSnippet from './code-snippet.spec.svelte'; describe('CodeSnippet', () => { const common = { language: 'json', code: '{ my: "json" }', }; it('Renders the code snippet', () => { render(CodeSnippet, common); const highlighted = hljs.highlight(common.code, { language: common.language, }); expect(screen.getByRole('code').innerHTML).toEqual( highlighted.value.replaceAll('"', '"') ); }); it('Renders with the copy button', async () => { const writeText = vi.fn(); Object.defineProperty(navigator, 'clipboard', { value: { writeText, }, }); render(CodeSnippet, common); const button = screen.getByRole('button', { name: /copy/iu, }); expect(button).toBeInTheDocument(); await userEvent.click(button); expect(writeText).toHaveBeenCalledWith(common.code); }); it('Renders without the copy button', () => { render(CodeSnippet, { ...common, showCopyButton: false }); const button = screen.queryByRole('button', { name: /copy/iu, }); expect(button).not.toBeInTheDocument(); }); it('Renders with a figcaption when the default slot is provided', () => { render(CaptionedCodeSnippet); expect(screen.getByText('This is the caption text.')).toBeInTheDocument(); }); it('Re-renders code block when code prop updates', async () => { const { rerender } = render(CodeSnippet, common); const initial = hljs.highlight(common.code, { language: common.language, }); expect(screen.getByRole('code').innerHTML).toEqual( initial.value.replaceAll('"', '"') ); const newCode = '{ their: "json" }'; const next = hljs.highlight(newCode, { language: common.language, }); await rerender({ ...common, code: newCode, }); expect(screen.getByRole('code').innerHTML).toEqual( next.value.replaceAll('"', '"') ); }); });