javascript - 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()
})
})
解决方案
推荐阅读
- python - 这个嵌套列表理解表达式是如何工作的?
- azure - 创建 3 个 VNET,其中所有流量都通过一个 VNET(中心辐射型)路由
- javascript - Mongo 并不总是返回正确的结果
- google-sheets - 谷歌表格 VLOOKUP 返回多个值
- android - 如何启动多个 FlutterActivity?
- unity3d - 如何从 Blender 中导出 .dae 动画?
- ios - 创建类似于 iOS 联系人的 UI 编辑 UI
- python - 如何创建一组 tkinter 小部件(for 循环)并单独引用它们中的每一个?
- netlogo - 协助 Netlogo 中的节点/链接导航
- tensorflow - 自定义层输出 Keras 的尺寸