Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set URL params while testing with Jest & Enzyme

My component has:

 class Search extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchTerm:
        typeof this.props.match.params.searchTerm !== "undefined"
          ? this.props.match.params.searchTerm
          : ""
    };
  }

and the test is:

 test("Search should render correct amount of shows", () => {
  const component = shallow(<Search shows={preload.shows} />);
  expect(component.find(ShowCard).length).toEqual(preload.shows.length);
});

I get

TypeError: Cannot read property 'params' of undefined

How can I fix that or how to set query params in my test?

like image 968
IceStrength Avatar asked Jan 23 '18 10:01

IceStrength


2 Answers

It seems like when outside the test, the Search component receives the match props correctly.
You could pass it as props when shallow rendering it in the test:

test("Search should render correct amount of shows", () => {
 const match = { params: { searchTerm: 'foo' } }
 const component = shallow(<Search shows={preload.shows} match={match}/>);
 expect(component.find(ShowCard).length).toEqual(preload.shows.length);
});

And in that case, you're not changing the component under test in a bad way, your test case just found a bug, which is good and should be aimed in tests, and you improved the component by implementing a default props, making it more robust.

like image 125
rodgobbi Avatar answered Oct 31 '22 15:10

rodgobbi


you should defined a location first in your it/test.

it('App init', async () => {
  const location = {
    ...window.location,
    search: '?scope=3&elementId=25924',
  };
  Object.defineProperty(window, 'location', {
    writable: true,
    value: location,
  })

  ……
})
like image 21
zhishaofei3 Avatar answered Oct 31 '22 15:10

zhishaofei3