我正在使用 create-react-app、Jest 和 react-testing-library 来配置聊天机器人项目。
我有一个使用 useRef 钩子的功能组件。当一条新消息到来时,会触发 useEffect 钩子并通过查看 ref 的当前属性引起滚动事件。
const ChatBot = () => {
const chatBotMessagesRef = useRef(null)
const chatBotContext = useContext(ChatBotContext)
const { chat, typing } = chatBotContext
useEffect(() => {
if (typeof chatMessagesRef.current.scrollTo !== 'undefined' && chat && chat.length > 0) {
chatBotMessagesRef.current.scrollTo({
top: chatMessagesRef.current.scrollHeight,
behavior: 'smooth'
})
}
// eslint-disable-next-line
}, [chat, typing])
return (
<>
<ChatBotHeader />
<div className='chatbot' ref={chatBotMessagesRef}>
{chat && chat.map((message, index) => {
return <ChatBotBoard answers={message.answers} key={index} currentIndex={index + …Run Code Online (Sandbox Code Playgroud) 我们有一个名为ScrollContainer的React组件,当它的内容滚动到底部时调用prop函数.
基本上:
componentDidMount() {
const needsToScroll = this.container.clientHeight != this.container.scrollHeight
const { handleUserDidScroll } = this.props
if (needsToScroll) {
this.container.addEventListener('scroll', this.handleScroll)
} else {
handleUserDidScroll()
}
}
componentWillUnmount() {
this.container.removeEventListener('scroll', this.handleScroll)
}
handleScroll() {
const { handleUserDidScroll } = this.props
const node = this.container
if (node.scrollHeight == node.clientHeight + node.scrollTop) {
handleUserDidScroll()
}
}
Run Code Online (Sandbox Code Playgroud)
this.container 在render方法中设置如下:
<div ref={ container => this.container = container }>
...
</div>
Run Code Online (Sandbox Code Playgroud)
我想用Jest + Enzyme测试这个逻辑.
我需要一种方法来强制clientHeight,scrollHeight和scrollTop属性成为我为测试场景选择的值.
使用mount而不是浅,我可以获得这些值,但它们始终为0.我还没有找到任何方法将它们设置为非零值.我可以设置容器wrapper.instance().container = { scrollHeight: 0 }等等,但这只会修改测试上下文而不是实际组件.
任何建议,将不胜感激!
我希望有人能指出我在useRef下面的组件中进行测试的正确方向。
我有一个结构如下的组件。我正在尝试测试其中的功能,otherFunction()但我不确定如何模拟来自组件引用的当前属性。有没有人做过这样的事情?
const Component = (props) => {
const thisComponent = useRef(null);
const otherFunction = ({ current, previousSibling }) => {
if (previousSibling) return previousSibling.focus();
if (!previousSibling && current) return current.focus();
}
const handleFocus = () => {
const {current} = thisComponent;
otherFunction(current);
}
return (
<div ref={thisComponent} onFocus={handleFocus}>Stuff In here</div>
);
};
Run Code Online (Sandbox Code Playgroud) Codesanbox链接-包括工作组件 Child2.js 和工作测试 Child2.test.js
Child2.js
import React, { useRef } from "react";
export default function Child2() {
const divRef = useRef();
function getDivWidth() {
if (divRef.current) {
console.log(divRef.current);
}
return divRef.current ? divRef.current.offsetWidth : "";
}
function getDivText() {
const divWidth = getDivWidth();
if (divWidth) {
if (divWidth > 100) {
return "ABC";
}
return "123";
}
return "123";
}
return (
<>
<div id="myDiv" ref={divRef}>
{getDivText()}
</div>
<p>Div width is: {getDivWidth()}</p>
</>
);
}
Run Code Online (Sandbox Code Playgroud)
Child2.test.js
import …Run Code Online (Sandbox Code Playgroud)