Javascript 使用Enzymejs测试呈现子组件
我正在尝试测试一个简单的组件,它使用Javascript 使用Enzymejs测试呈现子组件,javascript,reactjs,enzyme,Javascript,Reactjs,Enzyme,我正在尝试测试一个简单的组件,它使用Enzyme,使用一些道具(它没有状态或redux连接),它适用于像这样的普通元素,但是当我尝试测试子组件呈现的元素是否存在时,它失败了 我正在尝试使用mount,但它给我带来了很多错误,我是这方面的新手,因此,以下是我的代码: import React, { Component } from 'react'; import WordCloud from 'react-d3-cloud'; class PredictWordCloud extends Com
Enzyme
,使用一些道具(它没有状态或redux连接),它适用于像
这样的普通元素,但是当我尝试测试子组件呈现的元素是否存在时,它失败了
我正在尝试使用mount,但它给我带来了很多错误,我是这方面的新手,因此,以下是我的代码:
import React, { Component } from 'react';
import WordCloud from 'react-d3-cloud';
class PredictWordCloud extends Component {
render() {
const fontSizeMapper = word => Math.log2(word.value) * 3.3;
const { size, data, show } = this.props;
if (!show)
return <h3 className='text-muted text-center'>No data</h3>
return (
<section id='predict-word-cloud'>
<div className='text-center'>
<WordCloud
data={data}
fontSizeMapper={fontSizeMapper}
width={size}
height={300} />
</div>
</section>
)
}
}
export default PredictWordCloud;
import React,{Component}来自'React';
从“react-d3-cloud”导入WordCloud;
类PredictWordCloud扩展组件{
render(){
const fontSizeMapper=word=>Math.log2(word.value)*3.3;
const{size,data,show}=this.props;
如果(!show)
不返回任何数据
返回(
)
}
}
导出默认云;
它只是一个
的包装器,它直接从他的父母那里收到3个道具:
,其他任何东西
目前的测试非常简单:
import React from 'react';
import { shallow } from 'enzyme';
import PredictWordCloud from '../../components/PredictWordCloud.component';
import cloudData from '../../helpers/cloudData.json';
describe('<PredictWordCloud />', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<PredictWordCloud data={cloudData} size={600} show={true} />)
});
it('Render without problems', () => {
const selector = wrapper.find('#predict-word-cloud');
expect(selector.exists()).toBeTruthy();
});
});
从“React”导入React;
从“酶”导入{shall};
从“../components/PredictWordCloud.component”导入PredictWordCloud;
从“../../helpers/cloudData.json”导入cloudData;
描述(“”,()=>{
让包装纸;
在每个之前(()=>{
包装器=浅()
});
它('无问题渲染',()=>{
const selector=wrapper.find(“#predict word cloud”);
expect(selector.exists()).toBeTruthy();
});
});
现在它通过了但是如果我们将选择器更改为:const selector=wrapper.find('predict word cloud svg')
当svg
标记是
组件的返回时,测试失败,因为断言返回false
我尝试使用mount而不是shallow,完全相同的测试,但是我在mrreact-d3-cloud
上遇到了一个大错误:
PredictWordCloud呈现没有问题TypeError:无法读取null的属性“getImageData”
这特别奇怪,因为它只发生在测试环境中,UI和所有行为在浏览器中都能完美工作。您可以通过组件名称直接找到您的组件。 然后也可以在子组件内部使用find e、 g 或 您还可以通过以下方式比较生成的html结构:
it('Render without problems', () => {
const selector = wrapper.find('WordCloud').first();
expect(selector.html()).to.equal('<svg> Just an example </svg>');
});
it('Render without problems',()=>{
const selector=wrapper.find('WordCloud').first();
expect(selector.html()).to.equal('只是一个示例');
});
it('Render without problems', () => {
const selector = wrapper.find('WordCloud').first();
expect(selector.html()).to.equal('<svg> Just an example </svg>');
});