T
TanStack2y ago
ratty-blush

Mock react query with vitest

const { permissions } = queryClient.getQueryData( "validate" ) as ValidateInterface; How can I mock this example? I'm trying this way: vi.spyOn(queryClient, "getQueryData").mockImplementation( vi.fn().mockReturnValue({ validate: { permissions: permissions, partner_id: null, merchant_id: null, }, }) ); but it's not working.
4 Replies
adverse-sapphire
adverse-sapphire2y ago
Why would you test this implementation detail?
ratty-blush
ratty-blushOP2y ago
I'm using this permissions with a conditional to render some components like this
if (
permissions.register.merchant.merchant.merchant_list &&
!user.merchant_id
) {
return (
<Form.Item
data-test-id="form-item-merchant"
data-testid="form-item-merchant"
label={t(`table.merchant`)}
style={{ marginBottom: 10 }}
>
<MerchantSelect
queryOptions={filtersQuery}
setQueryFunction={setFiltersQuery}
/>
</Form.Item>
);
if (
permissions.register.merchant.merchant.merchant_list &&
!user.merchant_id
) {
return (
<Form.Item
data-test-id="form-item-merchant"
data-testid="form-item-merchant"
label={t(`table.merchant`)}
style={{ marginBottom: 10 }}
>
<MerchantSelect
queryOptions={filtersQuery}
setQueryFunction={setFiltersQuery}
/>
</Form.Item>
);
and when I run the test, I receive this error:
TypeError: Cannot read properties of undefined (reading 'register')
TypeError: Cannot read properties of undefined (reading 'register')
because the test didn't found the permission object.
adverse-sapphire
adverse-sapphire2y ago
Why do you access the value via queryClient and not useQuery? I recommend mocking the apiCall with mockServiceWorker
stormy-gold
stormy-gold2y ago
👆🏼

Did you find this page helpful?