2

Using enzyme, I'm attempting to test the rendered text of a component. The component is a LinkButton, and it renders out like so:

<a><button to="/projects">See list of all projects</button></a>

I'm not sure how to directly reference the string "See list of all projects". I'm currently testing it as follows:

let { link } = setup({ type: 'Project' })
link = link.shallow()

const text = link.prop('children').props.children.join('')
expect(link.prop('to')).to.eq('/projects')
expect(text).to.eq('See list of all projects')

link comes from shallow(<NotFoundCard />).find(LinkButton).

I've attempted to use link.find('button') and link.find('a') but both return 0 nodes.

edit 1

Code for setup:

const setup = propOverrides => {
  const props = Object.assign({
    children: null,
    type: 'None',
  }, propOverrides)

  const wrapper = shallow(<NotFoundCard {...props} />)

  return {
    props,
    wrapper,
    card: wrapper.find(Card),
    title: wrapper.find(CardTitle),
    text: wrapper.find(CardText),
    link: wrapper.find(LinkButton),
  }
}
Mark Chandler
  • 338
  • 1
  • 3
  • 9
  • 1
    `const text = link.text()` refer to this doc https://github.com/airbnb/enzyme/blob/master/docs/api/ReactWrapper/text.md – Rei Dien Mar 25 '17 at 04:32
  • Show your setup function. – Brigand Mar 25 '17 at 05:22
  • @FakeRainBrigand: Updated. – Mark Chandler Mar 25 '17 at 13:33
  • @ReiDien: I was able to get that method working using `mount` rather than `shallow`. – Mark Chandler Mar 25 '17 at 13:35
  • 1
    @MarkChandler if you are trying to test the stuff in LinkButton, then you should only test that component by itself using shallow. Try to not use mount. Then, make a different set of tests for the parent component(s) that use LinkButton; all you have to do is check that they pass the correct props to the LinkButton components. Again, make sure to use shallow and not mount. – nbkhope Mar 31 '17 at 18:39

1 Answers1

4

I think the right way to do this is to check the button element was passed a prop children with the value you want.

This test passes (it is using chai-enzyme)

describe('Link', () => {
  it('should have text', () => {
    const Link = () => (
      <a>
        <button to="/projects">See list of all projects</button>
      </a>
    );

    const wrapper = shallow(<Link />);
    expect(wrapper.find('button')).to.have.prop(
      'children',
      'See list of all projects'
    );
  });
});
JuanCaicedo
  • 3,132
  • 2
  • 14
  • 36
  • 5
    using jest the last line would be ` expect(wrapper.find('button').prop('children')).toEqual('See list of all projects ');` – P-A Apr 10 '19 at 06:57