I like the createContextHelper shorthand, but I don't find myself able to use it very often due to a particular pattern I use in my tests. I just thought I'd throw the idea out there, but I do have a workaround if this is more of a me thing.
I often create helpers which accept a Partial<T> of the context, and have the helper merge a default value with the partial. Using this type of helper I can keep my test focussed on just the part of the context I need to change, with the rest of the context set to some reasonable default (a fake value or jest.fn() for functions).
My current workaround is pretty simple:
const createPartialContextHelper = <ContextValue,>(
Context: React.Context<ContextValue>,
defaultValue: ContextValue
) =>
createHelper((value?: Partial<ContextValue>) => ({ children }) => (
<Context.Provider value={{ ...defaultValue, ...value }}>
{children}
</Context.Provider>
));
Which would be used the same as createContextHelper:
const Context = React.createContext<{ user: User, onEnter: () => void }>(...);
const withMyContext = createPartialContextHelper(Context, {
user: FakeUser,
onEnter: () => {},
});
But can be called with a Partial<T>:
it("calls onEnter sometime", () => {
const onEnter = jest.fn().mockWhatever();
render(<Something />, {
wrapper: wrap(withMyContext({ onEnter }))
})
...
})
I like the
createContextHelpershorthand, but I don't find myself able to use it very often due to a particular pattern I use in my tests. I just thought I'd throw the idea out there, but I do have a workaround if this is more of a me thing.I often create helpers which accept a
Partial<T>of the context, and have the helper merge a default value with the partial. Using this type of helper I can keep my test focussed on just the part of the context I need to change, with the rest of the context set to some reasonable default (a fake value orjest.fn()for functions).My current workaround is pretty simple:
Which would be used the same as
createContextHelper:But can be called with a
Partial<T>: