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. Basically I want to check if the changeName method is working

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>
);

Best Answer

There are a number of ways to assert the output of your component with enzyme, one approach is to use shallow render, e.g.

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, e.g.

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;
});