TheMayerof
TheMayerof

Reputation: 193

unit testing the output of a form in React.js, Jest, Enzyme

I am building a simple todo application in react, I am also testing using enzyme. I have just extracted the reder list into its own react component which works fine. I am attempting to mock a test for the output of this component but I am struggling.

The current result when I run the tests is

Expected: "New Note"
Received: <p><button onClick={[Function onClick]}>X</button></p>

the test currently looks like this...

describe('ListItems', () => {

  let wrapper;

  beforeEach(() => {
    const items = ['New Note', 'efefre', 'efqeecec'];
    wrapper = shallow(<ListItems list={[items]} />);
  });

  it('renders title of application', () => {
    expect(wrapper.find("h1").text()).toContain("This is the list")
  });

    it('renders the new note on the page', () => {
      const items = ['New Note']
      const wrapper = shallow(<ListItems list={items} />)
      const textOutput = wrapper.find("#text-output")
      expect(textOutput.props().children).toEqual("New Note")
  })
});

As you can see Im trying to mock a new array with a "New Note", an object is being passed through in my tests but just not the actual message. Where am I going wrong?

Just incase it helps this is the file that I am trying to test..

import React from 'react';

function ListItems(props) {
   const list = props.list
    const displayItems = list.map((item, index) => 
    {
      return <div id='text-output' key={index}>
            <p>
              {item.body}
              <button
              onClick={ () => props.deleteItem(item.id)}>
                X
              </button>
            </p>
        </div>
    })
  return(
  <div>
    <h1>This is the list</h1>
    {displayItems}
  </div>
  )
}

If anyone could help that would be great.

Upvotes: 0

Views: 327

Answers (2)

pritam
pritam

Reputation: 2558

Of course you will get the p and button elements when you find the div ID on your wrapper. If you need to assert the p element has a text 'New note' when you pass in as items array. You should use this

...
const textEl = wrapper.find("#text-output p"); // returns p element
expect(textEl.text()).toBe("New note");

Upvotes: 1

daniloxxv
daniloxxv

Reputation: 865

You are passing an array with a string ["New note"], but your code is actually expecting an array of objects with a body and an id. It is then trying (and failing) to render "New note".body, because that property does not exist. That's why you see this output:

<p><button onClick={[Function onClick]}>X</button></p>

If you replace ["New note"] with [{body: "New note", id: "some-id"}], your output will look more like this, which I believe is what you would expect:

<p>New note<button onClick={[Function onClick]}>X</button></p>

Upvotes: 1

Related Questions