我正在尝试测试在功能组件内部创建的散点图的创建。我尝试了很多软件包: Jest / Enzyme,Cheerio,react-test-renderer,测试库等。
html看起来像这样:
<div className="outerDiv" data-test='scatterchart'>
<div ref={wrapperRef} className="corrD3_wrapperDiv">
<svg ref={svgRef} className="corrD3_svgBox" xmlns="http://www.w3.org/2000/svg">
<defs>
<clipPath id={chartId}>
<rect x="0" y="0" width="100%" height="100%" />
</clipPath>
</defs>
<g className="x-axis" />
<g className="y-axis" />
<g className="content" clipPath={`url(#${chartId})`} />
</svg>
</div>
</div >
D3在useEffect内部生成。
我在测试代码中模拟了useEffect:
const mockUseEffect = () => {
useEffect.mockImplementation(f => f());
};
useEffect = jest.spyOn(React, 'useEffect');
mockUseEffect();
我在超时内运行测试,以允许useEffects。 在StackOverflow上找到:
// This is helper that I'm using to wrap test function calls
const withTimeout = (done, fn) => {
const timeoutId = setTimeout(() => {
fn();
clearTimeout(timeoutId);
done();
});
};
it('Should load component after timeout', done => withTimeout(done, () => {
let component;
component = mount(<Scatter2 {...props} />)
const $ = cheerio.load(component.html());
expect($('svg')).toHaveLength(1);
expect($('circle')).toHaveLength(20); <-- FAILS
}));
无论我做什么,在测试运行之前我都无法生成D3。
有人对我能做什么有建议吗? 我无法弄清楚。
谢谢, 杰德·K
答案 0 :(得分:0)
您是否尝试过将其包装在异步等待中?
import { wait } from "@testing-library/react";
it('Should load component after timeout', async () => {
let component;
component = mount(<Scatter2 {...props} />)
const $ = cheerio.load(component.html());
await wait(() => {
expect($('svg')).toHaveLength(1);
expect($('circle')).toHaveLength(20);
});