What are you trying to accomplish
I want to test that my code is rendering the BuilderComponent
. I don’t care what the BuilderComponent
outputs, so I don’t even need to specify a model or a public key, all I want to do is mock the BuilderComponent
, render my page, and see that BuilderComponent
was rendered on the page.
Code stack you are integrating Builder with
NextJS
Reproducible code example
Here’s the code I want to test:
import React from 'react';
import { builder, BuilderComponent } from '@builder.io/react';
export async function getStaticPaths() {
return {
paths: [],
fallback: 'blocking',
};
}
export async function getStaticProps({ params }) {
builder.init(params.siteId);
const footer = await builder.get('ecommerce-footer').toPromise();
return {
props: {
siteId: params.siteId,
footer: footer || null,
},
revalidate: 5,
};
}
export default function Footer({ siteId, footer }) {
builder.init(siteId);
return (
<BuilderComponent
model="ecommerce-footer"
content={footer}
options={{ includeRefs: true }}
/>
);
}
All this does is render my ecommerce-footer
model as a preview for users to edit as a section on their website. Here’s the test’s code:
import Footer from '@/pages/footer';
import * as builder from '@builder.io/react';
import { render } from '@testing-library/react';
jest.mock('@builder.io/react', () => ({
__esModule: true,
...jest.requireActual('@builder.io/react'),
}));
describe('Footer preview', () => {
it('renders successfully', () => {
const props = {
siteId: '12345',
footer: 'footer',
};
const builderInitSpy = jest.fn();
jest.spyOn(builder.builder, 'init').mockImplementation(builderInitSpy);
const MockBuilderComponent = jest.fn(() => <mock-builder-component />);
jest
.spyOn(builder, 'BuilderComponent')
.mockImplementation(MockBuilderComponent);
render(<Footer {...props} />);
expect(builderInitSpy).toHaveBeenCalledWith(props.siteId);
expect(MockBuilderComponent).toHaveBeenCalledWith({
model: 'ecommerce-footer',
content: 'footer',
options: { includeRefs: true },
});
});
});
I get errors like Error: Uncaught [TypeError: Cannot read properties of null (reading 'useContext')]
and Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
. Is there any documentation or tips on how to test around the BuilderComponent
so we can bring our unit test coverage to above 80%?