[英]How do you unit test a custom React function using enzyme, mocha, chai
My question is how I would test a custom function which changes a parameter. 我的问题是我将如何测试更改参数的自定义函数。 I want to test if a given uni such as 'University of cambridge passed as prob, will give me 'University...' as it should truncate after 10 characters.
我想测试给定的uni,例如“剑桥大学以概率形式通过”,是否会给我“大学...”,因为它应该在10个字符后截断。 Basically I want to check if the changeName method is working
基本上我想检查changeName方法是否正常
const University = ({ Name }) => (
renderUni(uniUrl, uniName) {
const truncateName = changenName(uniName);
return <Chevron className="chevronuni" /> {truncateName} + '...';
}
changeName(Name) {
const maxCharacterLength = 10;
if (Name.length > 10) {
return Name.substring(0, maxCharacterLength);
}
return Name;
}
<div className="uni">
<ul className="uni-login">
{Name &&
Name.map(({ uniUrl, uniName }) =>
(<li>
{renderUni(uniUrl, uniName)}
</li>)
)}
</ul>
</div>
);
There are a number of ways to assert the output of your component with enzyme, one approach is to use shallow render , eg 有多种方法可以用酶断言组分的输出,一种方法是使用浅色渲染 ,例如
const { shallow } = require('enzyme');
it('truncates the university name', () => {
const wrapper = shallow(<University Name={[ { uniUrl: '', uniName: 'University of Cambridge' } ]} />);
expect(wrapper.find('li').text()).to.be('University...');
});
If you're not particularly concerned about the finer details of your components output such as peripheral presentational mark-up / text you may find contains
to be of use, eg 如果您不特别关心组件输出的详细信息,例如外围设备的外观标记/文本,则可能会发现
contains
有用的内容,例如
const { shallow } = require('enzyme');
it('truncates the university name', () => {
const wrapper = shallow(<University Name={[ { uniUrl: '', uniName: 'University of Cambridge' } ]} />);
expect(wrapper.find('li').contains('University...')).to.be.true;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.