Why is jest not able to provide the useTranslation hook to a custom React hook I'm testing?

Viewed 181

I'm creating a test for a custom hook and checking if it parses data correctly. The custom hook uses the i18next useTranslation hook. I have mocked the useTranslation hook in the test file this way:

jest.mock('react-i18next', () => ({
  useTranslation: () => {
    return {
      t: (key: string) => key,
    }
  },
}))

It doesn't give me any errors, it just doesn't translate and returns the localization keys on the fields it has to translate. Am i mocking the wrong way or should I do some additional configuration?

1 Answers

I think there is a misconception about the mocking and testing purpose.

According to the Jest documentation:

Mock functions allow you to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with new, and allowing test-time configuration of return values.

If you want to test the functionality of your useTranslation hook, you can create a test (without mocking). in this way, you can test your hook functionality and behavior on different scenarios.

Now back to your code, if you want to test a component that uses an external function, you can mock this function and pass it to the component. So in this case you just need to mock the function and write some exceptions about it.

For example, you have a form component that has a submit button, with the submit, the data will be sent to the server, so you can mock this submit action and pass it to the component on test environment, then you expect that by clicking on submit button, the handler function invokes one time.

So if you want to mock your hook, you need to return mock data for it:

const mockMyHook = jest.fn(x => 'translated');

Now invoking this mock hock in your component and expect with an x input, get a tanslated value.

Related