How to test React components that depend on usePage? #675
-
I have a single component that is using
Normally, I would render the component in a test function, but I've tried wrapping the component in an
But that doesn't render anything:
How would you test such a component that depends on an Inertia page to exist? |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 5 replies
-
@claudiodekker any tips you have on testing components that use |
Beta Was this translation helpful? Give feedback.
-
Looking at your original snippet, this might work: const pageProps = {
props: {
authenticatedUser: {
name: "foo bar"
}
},
url: "\/test",
version: null
}
render(
<App
initialPage={pageProps}
resolveComponent={() => <Foobar />}
/>
)
// ... do some assertions It's not ideal though, currently looking into how we can improve this 👍 |
Beta Was this translation helpful? Give feedback.
-
Another possible solution is to wrap function useAuthenticatedUser() {
const { authenticatedUser } = usePage().props
return authenticatedUser;
}
export default function Foobar() {
const authenticatedUser = useAuthenticatedUser()
return (
<div>name: {authenticatedUser.name}</div>
)
}
// In tests…
jest.mock('../useAuthenticatedUser', () => ({ name: 'Pascal' })) |
Beta Was this translation helpful? Give feedback.
-
You don't need to render the App component in order to test Foobar. Something like this will work jest.mock('@inertiajs/inertia-react', () => ({
usePage: () => ({
props: {
authenticatedUser: {/* */}
}
})
}))
render(<Foobar />); |
Beta Was this translation helpful? Give feedback.
-
For those who encountered the same error with Storybook, I found mocking imports can be a solution. Here is my config// .storybook/__mocks__/inertia-react.js
import * as InertiaReact from '@inertiajs/inertia-react';
let inertiaSharedProps;
export function inertiaReactDecorator(story, { parameters }) {
if (parameters && parameters.inertia) {
inertiaSharedProps = parameters.inertia.sharedProps;
}
return story();
}
const mockUsePage = () => {
if (inertiaSharedProps) {
return {
props: inertiaSharedProps,
};
}
inertiaSharedProps = null;
}
InertiaReact.usePage = mockUsePage;
export default InertiaReact // .storybook/main.js
module.exports = {
...
webpackFinal: async (config) => {
config.resolve.alias['inertia-react'] = require.resolve('./__mocks__/inertia-react.js');
return config;
},
}; // .storybook/preview.js
import { inertiaReactDecorator } from './__mocks__/inertia-react';
export const decorators = [ ..., inertiaReactDecorator ] // Foo.stories.js
FooWithBarStatus.parameters = { inertia: { sharedProps: { isPublicPage: false } } }; P.s. I also tried wrapping the component with a |
Beta Was this translation helpful? Give feedback.
You don't need to render the App component in order to test Foobar. Something like this will work