为什么在测试中从未调用函数

问题描述 投票:0回答:1

我需要有关特定测试的帮助。我有一个组件,用于在我的项目中打开和关闭声音。最后一个测试,我尝试测试

e.prevenDefault
是否被调用不起作用,我不明白为什么。

我希望有人有想法。

import { useAppSelector, useAppDispatch } from '../../../../app/hooks';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faVolumeXmark} from '@fortawesome/free-solid-svg-icons';
import { faVolumeHigh} from '@fortawesome/free-solid-svg-icons';
import { RootState } from '../../../../app/store';
import { toggleMute } from '../../../../features/soundSlice/soundSlice';
import './SoundBtn.css';

export const SoundBtn = () => {
  const isMuted = useAppSelector((state: RootState) => state.sound.isMuted);
  const dispatch = useAppDispatch();

  // Prevent space key from triggering togglePlay
  const handleKeyDown = (e: React.KeyboardEvent<HTMLButtonElement>) => {
    if (e.code === ' ' || e.key === 'Space') {
      e.preventDefault(); 
    }
  };

  const togglePlay = () => {
    dispatch(toggleMute());
  };

  return (
    <button 
      className="commandBtn nonHoverBtn" 
      id='soundBtn' 
      onClick={togglePlay}
      onKeyDown={handleKeyDown}
    >
      {!isMuted ? (
        <FontAwesomeIcon 
          icon={faVolumeHigh} 
          className='soundBtnIcon'
          aria-label='click to mute sound'
        />
      ) : (
        <FontAwesomeIcon 
          icon={faVolumeXmark} 
          className='soundBtnIcon'
          aria-label='click to play sound'
        />
      )}
    </button>
  )
};

这个测试:

import { fireEvent, screen } from "@testing-library/react";
import { renderWithProviders } from "../../test-utils";
import { SoundBtn } from "../../../components/ui/buttons/soundBtn/SoundBtn";

describe('SoundBtn component', () => {
  it('renders the component and the correct button when muted without crashing', () => {
    const preloadedState = {
      sound: {
        isMuted: true, 
      },
    }; 

    renderWithProviders(<SoundBtn />, { preloadedState });

    expect(screen.getByLabelText('click to play sound')).toBeInTheDocument();
  });

  it('renders the component and the correct button when not muted without crashing', () => {
    const preloadedState = {
      sound: {
        isMuted: false, 
      },
    }; 

    renderWithProviders(<SoundBtn />, { preloadedState });

    expect(screen.getByLabelText('click to mute sound')).toBeInTheDocument();
  });

  it('toggles mute, when button is clicked', () => {
    const preloadedState = {
      sound: {
        isMuted: true, 
      },
    };
        
    const { store } = renderWithProviders(<SoundBtn />, { preloadedState });
    expect(store.getState().sound.isMuted).toBe(true);

    fireEvent.click(screen.getByLabelText('click to play sound'));

    const updatedState = store.getState().sound; 
    expect(updatedState.isMuted).toBe(false); 

    fireEvent.click(screen.getByLabelText('click to mute sound'));

    const newUpdatedState = store.getState().sound; 
    expect(newUpdatedState.isMuted).toBe(true); 
  });

  it('does not toggle sound, when space key is clicked', () => {
    const preloadedState = {
      sound: {
        isMuted: true, 
      },
    };
    const { getByLabelText } = renderWithProviders(<SoundBtn />);
    const button = getByLabelText('click to play sound');

    const preventDefaultSpy = vi.fn();

    const spaceEvent = new KeyboardEvent('keydown', { code: 'Space', key: ' ' });
    fireEvent.keyDown(button , spaceEvent);

    expect(preventDefaultSpy).toHaveBeenCalled();
    const { store } = renderWithProviders(<SoundBtn />, { preloadedState });
    expect(store.getState().sound.isMuted).toBe(true);
  });
});

对于最后一次测试,我收到错误:

FAIL  src/__tests__/components/ui/soundBtn.test.tsx > SoundBtn component > does not toggle sound, when space key is clicked
AssertionError: expected "spy" to be called at least once
 ❯ src/__tests__/components/ui/soundBtn.test.tsx:68:35
     66|         fireEvent.keyDown(button , spaceEvent);
     67| 
     68|         expect(preventDefaultSpy).toHaveBeenCalled();

 RERUN  src/__tests__/components/ui/soundBtn.test.tsx x149
javascript reactjs jestjs react-testing-library vitest
1个回答
0
投票

您是否尝试过将按钮设置为 onClick 事件来调用模拟函数?

const { getByLabelText } = renderWithProviders(<SoundBtn onClick={preventDefaultSpy} />);
© www.soinside.com 2019 - 2024. All rights reserved.