How to mock a single value in a React Context provider while keeping the rest of values

Viewed 879

Hi I have a context provider which returns like this:

return (
        <RepeatsSidebarContext.Provider
            value={{
                loading,
                designRepeats,
                handleShowCreateRepeatItem,
                handleShowCreateRepeatItemSmartSelvedge,
                createRepeatItem,
                handleCreateNewRepeat,
                handleCreateSmartSelvedge,
                nextRepeatName,
                handleUpdateRepeat,
                nativeRepeatsIcons,
                handleSortRepeats,
                onRepeatUpdate,
                createSmartSelvedgeItem,
            }}
        >
            {children}
        </RepeatsSidebarContext.Provider>
    );
};

export default RepeatsSidebarProvider;

And I would like only to mock the designRepeats value. It would be something like:

render(<RepeatsSidebarProvider value={{designRepeatsMock}}>
            <RepeatSidebarItem {...props} />
        </RepeatsSidebarProvider>)

But if I do like this, the prop value is set by only designRepeatsvalue so the rest of values get overwritten.

Would appreciate some help. thanks!

2 Answers

In your component you can use the context you have returned by useContext hook and alter the value of RepeatSidebarItem as you want it to be.

I found this way to mock the context with using a wrapper where I recreate the provider.

const wrapper = ({ children }) => (
            <RepeatsSidebarContext.Provider
                value={{
                    ...initialStateMock,
                    designRepeatsMock
                }}
            >
                {children}
            </RepeatsSidebarContext.Provider>
        );


    test("myTest",()=>{
render(<RepeatSidebarItem />, {wrapper})
})
Related