Mock UseMutation in react testing library and jest used in custom hook

Mock UseMutation in react testing library and jest used in custom hook


0

I have created a custom hook which is having several functions for processing the data and calling the functions. I am writing the test cases for few specific scenarios inside the hook. I will mention in the code below only functions specific to my case.

This is my custom hook : useShippingInformation.js

const useShippingInformation = () => {

  const [mutateShippingInformation, { data = {}, loading, error }] = useMutation(addShippingInformation, options)

const extensionAttributes = useMemo(() => {
    return isShippingMethodsOriginWeb
      ? {
          shipping_identifier: selectedShippingIdentifier,
        }
      : {
          delivery_date:
            shippingMethodCode === 'matrixrate' ? selectedDeliveryDate : null,
          delivery_time:
            shippingMethodCode === 'matrixrate' ? selectedDeliveryTime : null,
        }
  }, [
    isShippingMethodsOriginWeb,
    selectedShippingIdentifier,
    shippingMethodCode,
    selectedDeliveryDate,
    selectedDeliveryTime,
  ])

const setShippingInformation = () => {
    const address = getShippingAddress()
    mutateShippingInformation({
      variables: {
        addressInformation: {
          addressInformation: {
            extension_attributes: {
              ...extensionAttributes,
            },
          },
        },
      },
    })
  }

}

This is my test case file : useShippingInformation.test.js

import { renderHook, act } from '@testing-library/react'
import { ApolloProvider, useMutation } from '@apollo/client'
import useShippingInformation from './useShippingInformation'

jest.mock('@apollo/client', () => ({
  ...jest.requireActual('@apollo/client'),
  useMutation: jest.fn(), // We'll define this below
}))

// Mock React Router

jest.mock('next/router', () => ({
  ...jest.requireActual('next/router'),
  useRouter: jest.fn(),
}))

// Mock Custom Hooks

jest.mock('@framework/hooks', () => ({
  useStoreConfig: jest.fn(() => ({
    countryCode: 'ae',
    languageCode: 'en',
  })),
  useFeatureFlag: jest.fn(),
}))

// Mock All Context

jest.mock('@contexts/AuthContext', () => ({
  useAuthContext: jest.fn(() => ({})),
}))

jest.mock('@contexts/CheckoutContext', () => {
  const checkoutContextValue = {
    checkoutConfig: {
      shippingMethods: ['method1', 'method2'],
    },
    shippingAddressGuestForm: {
      countryId: 'AE',
      city: 'Dubai',
      address1: 'test',
      address2: '',
    },
    contactDetails: {
      firstname: 'Huzefa',
      lastname: 'Husain',
      phoneCode: '971',
      phoneNumber: '+97199999999',
    },
    setShippingInfoErrors: jest.fn(),
    setLoadingCheckout: jest.fn(),
    setAlert: jest.fn(),
    shippingMethodCode: 'someCode',
    selectedDeliveryDate: '2023-09-30',
    selectedDeliveryTime: '10:00 AM',
  }

  return {
    ...jest.requireActual('@contexts/CheckoutContext'),
    useCheckoutContext: jest.fn().mockReturnValue(checkoutContextValue),
  }
})

jest.mock('@contexts/CartContext', () => ({
  useCartContext: jest.fn(() => ({})),
}))

describe('useShippingInformation - extensionAttributes', () => {
  it('should return correct extensionAttributes when isShippingMethodsOriginWeb is true or false and specific values are provided to the payload', async () => {
    const mutateMock = jest.fn()

    useMutation.mockReturnValue([
      mutateMock, // This is the mutate function
      {
        data: null,
        loading: false,
        error: null,
      },
    ])

    const apolloClient = {
      query: jest.fn(),
    }

    const wrapper = ({ children }) => (
      <ApolloProvider client={apolloClient}>{children}</ApolloProvider>
    )

    const { result } = renderHook(() => useShippingInformation(), {
      wrapper,
    })

    // Set the extension attributes based on Shipping Methods Origin
    Object.defineProperty(result.current, 'isShippingMethodsOriginWeb', {
      get: jest.fn().mockReturnValue(true), // or false based on the test case
    })

    await act(() => result.current.setShippingInformation())

    expect(mutateMock).toHaveBeenCalledTimes(1)

    expect(mutateMock).toHaveBeenCalledWith({
      variables: {
        addressInformation: {
          addressInformation: {
            billing_address: {},
            shipping_address: {},
            shipping_carrier_code: '123',
            shipping_method_code: 'matrixrate',
            extension_attributes: {
              delivery_date: '2023-09-30',
              delivery_time: '10:00 AM',
            },
          },
        },
      },
      onCompleted: expect.any(Function),
      onError: expect.any(Function),
    })
  })
})

I have tried different ways to mock this but with no success. Below is the error I am getting:

expect(jest.fn()).toHaveBeenCalledTimes(expected)

Expected number of calls: 1
Received number of calls: 0

Expected:

  1. The mutation function is triggered
  2. The mutation is triggered with the variables below to check if the payload is correct based on the boolean value from isShippingMethodsOriginWeb constant.
variables: {
        addressInformation: {
          addressInformation: {
            billing_address: {},
            shipping_address: {},
            shipping_carrier_code: '123',
            shipping_method_code: 'matrixrate',
            extension_attributes: {
              delivery_date: '2023-09-30',
              delivery_time: '10:00 AM',
            },
          },
        },
      },


Load 4 more related questions


Show fewer related questions

0



Leave a Reply

Your email address will not be published. Required fields are marked *