首页 > 解决方案 > React 测试库不会重新渲染

问题描述

我试图在多个测试套件上重新渲染,但我总是做错事,我不知道是什么。

在 Dropdown 组件中有一个三元组控制应该渲染什么和不应该渲染什么。

import React, { useState, Fragment, useContext } from 'react';
import { library } from '@fortawesome/fontawesome-svg-core';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import useAuthContext from '../../hooks/useAuthContext/useAuthContext'
import { Link } from 'react-router-dom';
import {
  faCog,
  faMoon,
  faCaretDown,
  faUser,
  faOm
} from '@fortawesome/free-solid-svg-icons';
library.add(faCaretDown, faCog, faMoon, faUser);
const Dropdown = props => {
  const { isAuth, logoutReducer } = useAuthContext()
  const [active, setActive] = useState(false);
  let dropdownBody;
  const dropDownHandler = () => {
    setActive(!active);
  };
  if (active) {
    dropdownBody = (
      <ul className="dropdown__body">
  
        {isAuth ? (
          <>
            <li>
              <button onClick={logoutReducer}>Logout</button>
            </li>
          </>
        ) : (
          <>
            <li>
              <Link data-testid="signup" to="/signup">
                SignUp
              </Link>
            </li>
            <li>
              <Link data-testid="login" to="/login">
                Login
              </Link>
            </li>
          </>
        )}
      </ul>
    );
  }
  return (
    <div className="dropdown">
      {dropdownBody}
    </div>
  );
};
export default Dropdown;

  describe('<Dropdown/>',() => {
    afterEach(cleanup)
    it('calling render with the same component on the same container does not remount', () => {
        const authState = {
            isAuth:false,userId:null,token:null,userData:null
          }
        const { container,getByText,getByTestId,rerender } = render (<Dropdown  />,{wrapper: ({ children }) => (
            <AuthContextTestWrapper authState={authState} children={children} />
            )})
       
        let signUpButton = (waitForElement(() => getByText('SignUp')))
        let loginButton = (waitForElement(() => getByText('Login')))
        expect(signUpButton).toBeTruthy()
        expect(loginButton).toBeTruthy()
        rerender(<Dropdown  />,{wrapper: ({ children }) => (
            <AuthContextTestWrapper authState={authState} children={children} />
            )})

         signUpButton = (waitForElement(() => getByText('SignUp')))
         loginButton = (waitForElement(() => getByText('Login')))

       // This part comes as truthy
        expect(signUpButton).toBeFalsy()
        expect(loginButton).toBeFalsy()
      })
   
  })

标签: javascriptreactjsunit-testingjestjsreact-testing-library

解决方案


推荐阅读