首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在react中测试滑块组件

在react中测试滑块组件
EN

Stack Overflow用户
提问于 2021-06-29 04:00:02
回答 1查看 40关注 0票数 0

我想用react测试库测试我的滑块组件。但我无法理解如何正确地测试它。我想测试当用户单击点(StyledDotContainer)时更改幻灯片。StyledDotContainer的背景是灰色的,但当活动道具为true时,它是红色的。该组件如下所示。

代码语言:javascript
运行
复制
const Slider = ({
  children,
  autoPlayTime = 5000,
  dots = true,
  initialIndex= 0
}: SliderProps): React.ReactElement => {
  const [activeIndex, setActiveIndex] = useState<number>(initialIndex)

  const nextSlide = () => {
    const newIndex = activeIndex >= length - 1 ? 0 : activeIndex + 1
    setActiveIndex(newIndex)
  }
  useEffect(() => {
    const timer = setTimeout(() => {
      nextSlide()
    }, autoPlayTime)
    return () => clearTimeout(timer)
  }, [activeIndex])

  const length = useMemo(() => {
    return React.Children.count(children)
  }, [])

  const setSlide = useCallback((index: number) => {
    setActiveIndex(index)
  }, [])

  const value = useMemo(() => ({ activeIndex, setSlide }), [activeIndex])

  return (
    <SliderContext.Provider value={value}>
      <StyledContainer>
        {children}
        {dots && (
          <StyledDotsContainer data-testid="dots">
            {[...Array(length)].map((_, index) => {
              return (
                <StyledDotContainer
                  data-testid={`dot-${index}`}
                  key={index}
                  onClick={() => setSlide(index)}
                  isActive={index === activeIndex}
                />
              )
            })}
          </StyledDotsContainer>
        )}
      </StyledContainer>
    </SliderContext.Provider>
  )
}

感谢您的建议。

EN

Stack Overflow用户

发布于 2021-06-29 05:06:36

测试组件的样式是一种糟糕的做法。相反,您只想测试您正在尝试测试的函数是否正确地更改了组件中的属性。样式应该在视觉上进行检查。

代码语言:javascript
运行
复制
import screen from '@testing-library/dom'
import {render, screen} from '@testing-library/react'
import userEvent from '@testing-library/user-event'

describe("Slider", () => {

  it('Should be red when slider is active', () => {
    render(Slider)

    const firstDot = screen.getByTestId('dots-0')

    act(() => {
      userEvent.click(firstDot)
    })

    waitFor(() => {
      expect(screen.getByTestId('dots-0').props.isActive).toBeTruthy()
    })
  })
})
票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68169371

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档