0

I am writing a React component that wraps an external web-component. Since this is external I want to wrap it in an error boundary.

Everything works in production, but I encounter some problems when testing with Vitest mocks.

This is what I have so far after doing some research online.

File: jsx.d.ts

declare namespace JSX {
    interface IntrinsicElements {
        "footer-external": { "description": string }
    }
}

File: Footer.tsx

import {ErrorBoundary} from "react-error-boundary";

export const Footer = () => {
    return (
        <ErrorBoundary fallback={<div>Error loading footer</div>}>
            <footer-external description="This is the description" data-testid="external-footer-id"/>
        </ErrorBoundary>
    );
}

File: Footer.test.tsx

vi.mock('react', async (importOriginal) => {
    const mod = await importOriginal<typeof import("react")>()
    const originalCreateElement = mod.createElement;

    console.log("I also expect to see this and I do not");
    return {
        ...mod,
        createElement: (type: string,
                        props: (InputHTMLAttributes<HTMLInputElement> & ClassAttributes<HTMLInputElement>) | null | undefined,
                        ...children: ReactNode[]) => {
            if (type === 'footer-external') {
                throw new Error('footer-external exception')
            }
            return originalCreateElement(type, props, ...children)
        },
    };
});

describe("Footer", () => {
    test("Renders error boundary when exception is thrown", () => {
        render(<Footer/>)
        expect(screen.getByTestId("external-footer-id")).not.toBeInTheDocument()
        expect(screen.getByText("Error loading footer")).toBeInTheDocument()
    })
})

Error:

Error: expect(element).not.toBeInTheDocument()

expected document not to contain element, found <footer-external
  data-testid="external-footer-id"
  description="This is the description"
/> instead

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.