Rule typescript:S2187 not understanding it.each

  • ALM used: GitHub
  • CI system used: GHA
  • Scan
  • TypeScript

False positive issue for rule typescript:S2187 when using it.each which is IMO a pretty good practice and elegant way to test several cases.

The file in question:

import { useDispatch } from 'react-redux';
import { describe, it, expect, Mock } from 'vitest';

import { renderHook, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

import { KeysCombinations, onKeyPress } from '@hmi/core-features-events';

import { useKeys } from '../useKeys';

vi.mock('react-redux', () => ({
  useDispatch: vi.fn(),
}));

describe('useKeys', () => {
  let dispatchMock: Mock;

  beforeEach(() => {
    dispatchMock = vi.fn();
    (useDispatch as unknown as Mock).mockReturnValue(dispatchMock);
  });

  it.each`
    key                        | expectedAction
    ${'{Alt>}a{/Alt}'}         | ${onKeyPress(KeysCombinations.altA)}
    ${'{Control>}a{/Control}'} | ${onKeyPress(KeysCombinations.ctrlA)}
  `(
    'should dispatch onKeyPress action when $key is pressed',
    async ({ key, expectedAction }) => {
      renderHook(() => useKeys());

      // Simulate key press
      await act(async () => {
        await userEvent.keyboard(key);
      });

      // Verify that the correct action has been dispatched
      expect(dispatchMock).toHaveBeenCalledWith(expectedAction);
    },
  );
});
1 Like

Hi Pierre,

Sorry for the late response. Thanks for reaching and welcome to the community!

You are right; it is a false positive since the rule understands it.each for other test libs but not yet for Vitest.

If several of your tests are like this, you can consider disabling the rule for now.

I created a ticket to track this and take it into consideration later on:
https://sonarsource.atlassian.net/browse/JS-180

We are interested in having better support for Vitest and patterns used by the community, like this one you pointed out. Feel free to share other things you find when using Sonar with Vitest!

1 Like

We’re getting the same issue with Jest. If a file contains only it.each tests it will trigger the false positive

Hello Elliot,
I’ve updated the ticket with your comment.

Kind regards,
Michal

2 Likes