2021-07-21 09:30:18 +00:00
|
|
|
import type { Context } from "react";
|
|
|
|
import { useContext } from "react";
|
2022-07-07 05:23:54 +00:00
|
|
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
2021-07-21 09:30:18 +00:00
|
|
|
import useRequiredContext from "./useRequiredContext";
|
|
|
|
|
2022-07-07 05:23:54 +00:00
|
|
|
vi.mock("react");
|
2021-07-21 09:30:18 +00:00
|
|
|
|
2022-07-07 05:23:54 +00:00
|
|
|
const useContextMock = vi.mocked(useContext);
|
2021-07-21 09:30:18 +00:00
|
|
|
|
|
|
|
describe("useRequiredContext", () => {
|
|
|
|
beforeEach(() => {
|
|
|
|
useContextMock.mockReset();
|
|
|
|
});
|
|
|
|
|
|
|
|
it("resolves the context", () => {
|
|
|
|
const context = {} as Context<unknown>;
|
|
|
|
const resolved = "FakeValue";
|
|
|
|
|
|
|
|
useContextMock.mockReturnValue(resolved);
|
|
|
|
|
|
|
|
expect(useRequiredContext(context)).toEqual(resolved);
|
|
|
|
});
|
|
|
|
|
|
|
|
it("throws if a named context cannot be resolved", () => {
|
|
|
|
const displayName = "FakeDisplayName";
|
|
|
|
const context = { displayName } as Context<unknown>;
|
|
|
|
const expected = `No provider found for the '${displayName}' context, make sure it is included in your component hierarchy.`;
|
|
|
|
|
|
|
|
useContextMock.mockReturnValue(undefined);
|
|
|
|
expect(() => useRequiredContext(context)).toThrow(expected);
|
|
|
|
|
|
|
|
useContextMock.mockReturnValue(null);
|
|
|
|
expect(() => useRequiredContext(context)).toThrow(expected);
|
|
|
|
});
|
|
|
|
|
|
|
|
it("throws if an unnamed context cannot be resolved", () => {
|
|
|
|
const context = {} as Context<unknown>;
|
|
|
|
const expected =
|
|
|
|
"No provider found for an unknown context, make sure it is included in your component hierarchy.";
|
|
|
|
|
|
|
|
useContextMock.mockReturnValue(undefined);
|
|
|
|
expect(() => useRequiredContext(context)).toThrow(expected);
|
|
|
|
|
|
|
|
useContextMock.mockReturnValue(null);
|
|
|
|
expect(() => useRequiredContext(context)).toThrow(expected);
|
|
|
|
});
|
|
|
|
});
|