如何使用酶,mocha,chai对自定义React函数进行单元测试

时间:2017-01-11 20:30:17

标签: javascript reactjs mocha chai enzyme

我的问题是如何测试更改参数的自定义函数。我想测试一个特定的大学,如'剑桥大学是否通过概要,将给我'大学...',因为它应该截断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>
);

1 个答案:

答案 0 :(得分:0)

有很多方法可以用酶来断言组件的输出,一种方法是使用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...');
});

如果您不特别关注组件输出的更精细细节,例如外设表示标记/文本,您可能会发现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;
});
相关问题