酶等待 useEffect 和状态更新

时间:2021-02-13 21:50:38

标签: reactjs jestjs enzyme

我有一个组件,它使用自定义钩子来测量 div 的高度和宽度,然后更新 useEffect 中的状态(下面的代码)。然后我想测试一个 div 在依赖于 useEffect 更新的子组件中呈现。我对单元测试很陌生,但我认为它会像这样简单:

const wrapper =  mount(<Board piecesToRender={piecesToRender} />)
const components = findByTestAttr(wrapper, 'component-piece')
expect(components.length).toBe(piecesToRender.length)

然后尝试这个:

const wrapper = await mount(<Board piecesToRender={piecesToRender} />)
act(() => {
    const components = findByTestAttr(wrapper, 'component-piece')
    expect(components.length).toBe(piecesToRender.length)
}) 

我知道它有效,因为我可以在浏览器中看到它,但我不知道如何使我的测试有效。

感谢一位前端开发人员怀疑测试驱动开发的世界是否真的适合我!!!

const Board: board = ({piecesToRender}) => {
    const [ref, {width, height}] = useMeasure();
    const [boardSize, setBoardSize] = useState<number>(300);
    const [squareSize, setSquareSize] = useState<null | number>(null);


    useEffect(() => {
        const max = (width > height) ? height : width
        setBoardSize(max)
        setSquareSize(max / 8)
    }, [width, height])

    const pieceElements = squareSize && piecesToRender.map(({color, name, position}) => <Piece squareSize={squareSize}
                                                                                  color={color} name={name} position={position}/>)

    return (<>
            <div
                ref={ref as string | ((instance: HTMLDivElement | null) => void) | RefObject<HTMLDivElement> | null | undefined}
                data-test={"component-container"} className={styles.Container}>
                <div data-test={"component-board"} style={{height: boardSize, width: boardSize}}
                     className={styles.Board}>
                    {boardColors.map((color, index) => (
                        <Square key={color + index} color={color}/>
                    ))}
                </div>
                {pieceElements}
            </div>
        </>
    )
}

0 个答案:

没有答案