How do I write a unit test case in enzyme for an action inside useEffect

Viewed 19

Hi I am writing a code which triggers an action inside a useEffect hook. It is something like this:

useEffect(() => {
    if (error && vehicle && onInstallError) {
      onInstallError({
        action: "validateTireSize",
        message: "find tires that fit",
        warranty: planSkuName,
        vehicle: `${vehicle.year}|${vehicle.make}|${vehicle.model}`
      });
    }
  }, [error, onInstallError, vehicle, planSkuName]);

Now I need to write unit test in Enzyme for it to have 100% code coverage. Could someone help me in this

1 Answers

You can write a unit test to test an action in an useEffect hook by mocking the action and verifying it is being called.

Here is an example snippet.

// component.spec.ts

// import the actions into the test.
import { onInstallError } from './my-actions';

// mock the actions module to watch the onInstallError function.
jest.mock('./my-actions');

beforeEach(async () => {
     await act(async () => {
        render(<MyComponent />);
    });
});

test('calls onInstallError on error', () => {
    expect(onInstallError)
        .toHaveBeenCalledWith({
            action: "validateTireSize",
            message: "find tires that fit",
            warranty: '1',
            vehicle: `2012|toyota|tacoma`
        });
})

Obviously, the error and vehicle variables in your component will need to be truthy to verify it is called.

Related