你如何使用 enzyme、mocha、chai 对自定义 React 函数进行单元测试
How do you unit test a custom React function using enzyme, mocha, chai
我的问题是如何测试更改参数的自定义函数。我想测试给定的 uni(例如“剑桥大学”作为概率通过)是否会给我 'University...',因为它应该在 10 个字符后截断。基本上我想检查 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>
);
有多种方法可以使用酶断言组件的输出,一种方法是使用 shallow render,例如
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...');
});
如果您不是特别关心组件输出的更精细细节,例如外围表示 mark-up / 文本,您可能会发现 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;
});
我的问题是如何测试更改参数的自定义函数。我想测试给定的 uni(例如“剑桥大学”作为概率通过)是否会给我 'University...',因为它应该在 10 个字符后截断。基本上我想检查 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>
);
有多种方法可以使用酶断言组件的输出,一种方法是使用 shallow render,例如
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...');
});
如果您不是特别关心组件输出的更精细细节,例如外围表示 mark-up / 文本,您可能会发现 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;
});