I have a provider component that provides a context with a function. If the provider component is not a parent of whatever component is consuming the context, the function from the context throws an error.
Here is the test component I am creating to consume the context:
function TestConsumerComponent({ toastData }) {
const { createToast } = useContext(ToastQueueContext);
return (
<button
data-testid="createToastButton"
onClick={() => createToast(toastData)}
></button>
);
}
So essentially, if this component does not have the provider as its parent, clicking the button should throw an error.
Here is the Vitest test I am using to test that expected error:
test("context function createToast() expected to error if no parent provider", () => {
expect(() => {
const { getByTestId } = render(
<TestConsumerComponent toastData={toastDataArray[0]} />,
);
fireEvent.click(getByTestId("createToastButton"));
}).toThrowError(
/^createToast can only be used inside <ToastQueueContext.Provider>$/,
);
});
When I run the test, the test fails, and also Vitest warns of an uncaught exception thrown. This leads me to believe that the error is somehow being thrown after the test is completed as failed.
Things I have tried:
- Leaving argument for
toThrowError()
empty. Same result. - Wrapping the test in an
act()
from testing-library/react. Interestingly this causes the button to not be found withgetByTestId()
? - Just throwing an Error directly in the test, which passes fine, but isn’t what I need.
Here is a codesandbox.io link (codesandbox.io) to try the test yourself with “npm run test” in the console. The test is labeled “context function createToast() expected to error if no parent provider”. Any ideas are appreciated.