Search code examples
reactjsunit-testingreact-testing-library

React testing library wrapper component


i seem to be stuck with an issue, i have a component which inside has a template wrapper around the jsx, this template wrapper is the header with tabs etc it looks like this:

const Component =() => { return ( <TemplateWrapper> all the components jsx content </TemplateWrapper> ) }

when i render the Component all i get is the TemplateWrapper content and none of the page jsx content that i would like to test. so if anyone can help, how do i render the page content and not just the TemplateWrapper components content? thanks for any help

I tried to mock the TemplateWrapper, but this didnt seem to work,

jest.mock(/TemplateWrapper, () => ({TemplateWrapper: jest.fn()}))

I also tried to use beforeAll to execute the mock wrapper.


Solution

  • In your mock, you're currently replacing the entire TemplateWrapper component with a mock function. If you want to keep the children intact, you need to make sure your mock function returns its children.

    you could use a mock function like this as an example:

    jest.mock('./TemplateWrapper', () => {
        return {
            __esModule: true,
            default: jest.fn(({children}) => <div>{children}</div>)
        };
    });
    

    In the above mock, we're replacing TemplateWrapper with a mock function that returns a div that contains all its children. Now when you use TemplateWrapper in your tests, it should render its children as expected.

    Remember to replace './TemplateWrapper' with the actual path to your TemplateWrapper component.