Search code examples
javascriptreactjsreact-context

Moving context definition to separate file from provider breaking tests


I have a React.createContext and the context.provider instance that I am using with my code and initially had them in the same file as it is always shown within demonstrations and the official docs.

I however, have decided to move the React.createContext() into a different file alongside other exported functions that make use of it.

Since doing this, I have noticed that my tests are breaking around an area that has nothing to do with the files being tests/used...

I'm just wondering if there was an obvious reason why my context wouldn't work properly after I'd put them into separate files?

MyContext/index.js

export const MyContext = React.createContext({});

MyContext/MyProvider.js

return <MyContext.Provider value={{data: 'some-data'}}>
    {children}
</MyContext.Provider>

MyContext/MyProvider.test.js

it('Should render child of provider', () => {
    let component;

    act(() => {
        component = renderer.create(
            <MyProvider>test test</MyProvider>
        );
    });

    expect(component.toJSON()).toMatchSnapshot();
});

Solution

  • It looks like the main issue was that my context was within the main index.js file that is exported...

    Moving this code to another file helped everything work.