如何在React组件中针对(非DOM)“引用”进行测试?

时间:2019-04-26 08:24:13

标签: javascript reactjs unit-testing enzyme react-hooks

我有一个看起来像这样的组件:

function MyComponent({elements}) {
    const elementRef = useRef(null);
    const chartRef = useRef(null);

    useEffect(() => {
        if (elementRef !== null) {
            chartRef.current = chart(/* options to init chart */)
        }
    }, []);

    return (
        <div ref={elementRef} />
    );
}

我想测试该组件,但是我想到的唯一有意义的测试方法是通过从测试代码访问chartRef.current

it("renders the chart", () => {
    const chartComponent = mount(
        <Cytoscape elements={[/**/]} />
    );

    // If somehow I can access `chartRef.current`:
    assertThat(chartRef.current.elements, equalTo(elements));
});

0 个答案:

没有答案