1

I would like to test that clicking on a link updates the components in my app.

Here's my app, when you click on about it renders the About component

import React, { Component } from 'react';
import './App.css';
import {
  MemoryRouter as Router,
  Route,
  Link
} from 'react-router-dom'


const Home = () => <h1>home</h1>
const About = () => <h1>about</h1>

class App extends Component {
  render() {
    return (
      <Router>
        <ul>
          <li><Link to="/about">About</Link></li>
          <li><Link to="/">Home</Link></li>
        </ul>
        <Route exact path="/" component={Home}/>
        <Route path="/about" component={About}/>
      </Router>
    );
  }
}

export default App;

And here's my test:

import React from 'react';
import Adapter from 'enzyme-adapter-react-16';
import Enzyme from 'enzyme';
import { mount } from "enzyme";
import { MemoryRouter} from 'react-router-dom'
import App from './App';

Enzyme.configure({ adapter: new Adapter() });


// this test passes as expected
it('renders intitial heading as home', () => {
  const wrapper = mount(
    <App />
  );

  const pageHeading = wrapper.find("h1").first().text()
  expect(pageHeading).toEqual('home');
});

it('renders about heading when we navigate to about', () => {
  const wrapper = mount(
    <App />
  );

  const link = wrapper.find("Link").first();
  link.simulate('click');

  const pageHeading = wrapper.find("h1").first().text()
  expect(pageHeading).toEqual('about');
});

The second test fails:

FAIL  src/App.test.js
  ● renders about heading when we navigate to about

    expect(received).toEqual(expected)

    Expected value to equal:
      "about"
    Received:
      "home"

I'm using react router v4, react 16 and enzyme 3.1

Is it possible to test in this way using React Router and enzyme?

Finnnn
  • 3,530
  • 6
  • 46
  • 69

1 Answers1

6

Link's render function will check for event.button === 0. That's why check fails with enzyme if you call simulate without proper params.

Try link.simulate('click', { button: 0 });

Good luck.

fung
  • 641
  • 6
  • 14
  • Brilliant find!! So happy I found this, thank you @fund & @Finnnn, I did a bit of digging afterwards to discover what button: 0 means and whether it's safe to put on all events. Looking a the Link render code this comment reveals the meaning ``` event.button === 0 && // ignore right clicks```. So for my tests I will use this fix everywhere as I'm not concerned about right clicks. Also FYI an Enzyme discussion about why it isn't a default... https://github.com/airbnb/enzyme/issues/516 – Keegan 82 Jul 10 '18 at 11:38
  • My name is Fung – fung Nov 21 '22 at 13:31