Erreur de la bibliothèque de tests React : non détectée
P粉917406009
P粉917406009 2024-03-29 15:27:26
0
1
302

J'ai un composant de réaction

import React, { useEffect, useRef, useState } from 'react';
import './PopularBrands.scss';
import LG from '../../../assets/images/brands/LG.png';
import Google from '../../../assets/images/brands/Google.jpeg';
import Apple from '../../../assets/images/brands/Apple.png';
import Boch from '../../../assets/images/brands/Boch.png';
import Dyson from '../../../assets/images/brands/Dyson.png';
import Philips from '../../../assets/images/brands/Philips.png';
import Samsung from '../../../assets/images/brands/Samsung.png';
import Simens from '../../../assets/images/brands/Simens.png';
import Sony from '../../../assets/images/brands/Sony.png';
import Xiomi from '../../../assets/images/brands/Xiomi.png';
import { FaChevronLeft } from 'react-icons/fa';
import { FaChevronRight } from 'react-icons/fa';

const PopularBrands = () => {
  const scrollViewRef = useRef<HTMLDivElement | null>(null);
  const [screenWidth, setScreenWidth] = useState(0);
  const [width, setWidth] = useState(0);
  const [widthTotal, setWidthTotal] = useState(0);
  const [showArrow, setShowArrow] = useState(false);

  useEffect(() => {
    function handleWindowResize() {
      if (scrollViewRef.current) setWidth(scrollViewRef.current.clientWidth);
      if (scrollViewRef.current) setWidthTotal(scrollViewRef.current.scrollWidth);
    }

    handleWindowResize();

    window.addEventListener('resize', handleWindowResize);

    return () => {
      window.removeEventListener('resize', handleWindowResize);
    };
  }, []);

  useEffect(() => {
    scrollViewRef.current?.scrollTo({ left: screenWidth, behavior: 'smooth' });
  }, [screenWidth]);

  const toNextPage = () => {
    if (scrollViewRef && screenWidth <= widthTotal) {
      setScreenWidth(screenWidth + width);
    }
  };

  const toPreviosPage = () => {
    if (scrollViewRef && screenWidth >= 0) {
      setScreenWidth(screenWidth - width);
    }
  };

  return (
    <div
      className="brandsContainer"
      onMouseEnter={() => setShowArrow(true)}
      onMouseLeave={() => setShowArrow(false)}>
      <div className="brands" ref={scrollViewRef}>
        <div>
          <img src={LG} alt="lg" />
        </div>
        <div>
          <img src={Google} alt="Google" />
        </div>
        <div>
          <img src={Apple} alt="Apple" />
        </div>
        <div>
          <img src={Boch} alt="Boch" />
        </div>
        <div>
          <img src={Dyson} alt="Dyson" />
        </div>
        <div>
          <img src={Philips} alt="Philips" />
        </div>
        <div>
          <img src={Samsung} alt="Samsung" />
        </div>
        <div>
          <img src={Simens} alt="Simens" />
        </div>
        <div>
          <img src={Sony} alt="Sony" />
        </div>
        <div>
          <img src={Xiomi} alt="Xiomi" />
        </div>
      </div>
      {screenWidth > 0 && showArrow && (
        <div className="scrollIcon scrollBack" onClick={toPreviosPage}>
          <FaChevronLeft fontSize={30} />
        </div>
      )}

      {screenWidth + width < widthTotal && showArrow && (
        <div className="scrollIcon scrollNext" onClick={toNextPage}>
          <FaChevronRight fontSize={30} />
        </div>
      )}
    </div>
  );
};

export default PopularBrands;

Cela fonctionne bien dans l'interface utilisateur. Mais quand j'écris le test unitaire suivant :

import React from 'react';
import { render, screen } from '@testing-library/react';
import PopularBrands from './PopularBrands';

describe('PopularBrands', () => {
  test.only('renders the component', () => {
    render(<PopularBrands />);

    expect(screen.getByAltText('lg')).toBeInTheDocument();
    expect(screen.getByAltText('Google')).toBeInTheDocument();
    expect(screen.getByAltText('Apple')).toBeInTheDocument();
    expect(screen.getByAltText('Boch')).toBeInTheDocument();
    expect(screen.getByAltText('Dyson')).toBeInTheDocument();
    expect(screen.getByAltText('Philips')).toBeInTheDocument();
    expect(screen.getByAltText('Samsung')).toBeInTheDocument();
    expect(screen.getByAltText('Simens')).toBeInTheDocument();
    expect(screen.getByAltText('Sony')).toBeInTheDocument();
    expect(screen.getByAltText('Xiomi')).toBeInTheDocument();
  });
});

Le test a échoué et j'ai obtenu le journal des erreurs :

● PopularBrands › renders the component

    TypeError: _scrollViewRef$curren.scrollTo is not a function

      37 |
      38 |   useEffect(() => {
    > 39 |     scrollViewRef.current?.scrollTo({ left: screenWidth, behavior: 'smooth' });
         |                            ^
      40 |   }, [screenWidth]);
      41 |
      42 |   const toNextPage = () => {

      at src/components/Directory/PopularBrands/PopularBrands.tsx:39:28

J'essaie d'obtenir de l'aide pour corriger mes tests unitaires. Il existe une dépendance de screenWidth sur la fonction useEffect et lorsque cela change, nous faisons défiler jusqu'au début de la liste des icônes.

P粉917406009
P粉917406009

répondre à tous(1)
P粉256487077

J'ai également rencontré un problème similaire. J'ai réussi le test et éliminé l'erreur en ajoutant ce qui suit :

Element.prototype.scrollTo = jest.fn();

En ajoutant ceci à votre fichier setupTests, cela devrait éliminer les erreurs, mais comme c'est une simulation, vous ne pourrez plus tester la fonctionnalité éther.

De plus, j'aime le fait que la bibliothèque de tests n'est pas prête ou équipée pour tester les événements de défilement, si vous souhaitez les tester, vous avez besoin d'un environnement de test basé sur un navigateur, pas d'un nœud comme jest et test-library.

J'espère que cela vous aidera.

Edit 1 :

Mais vous pouvez tester si la fonction a été appelée, par exemple :

expect(Element.prototype.scrollTo).toHaveBeenCalled();
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!