react-router v4 Link doesn't work in karma test runner

Pavel Poberezhnyi Source

I would like to write some specs to test my current routing in my app. I use karma to run my specs and mocha as test framework. Everything works fine until I click on some <Link /> component. Event onclick launched but it doesn't trigger re-rendering my components and, hence, nothing changes (app doesn't render new <Match /> routers). My current code:

<!-- language: lang-js -->
'use strict';
import React from 'react';
import { BrowserRouter, Match, Redirect } from 'react-router';
import { shallow, mount } from 'enzyme';
import sinon from 'sinon';
import chai, { expect } from 'chai';
import axios from 'axios';
import Main_Store from '../../';
import Base from '../../components/base.component';

describe.only('--Routing--', () => {
   let main_store, wrap;
   beforeEach(() => {
      main_store = new Main_Store();
      wrap = mount(
         <MemoryRouter initialIndex={1} initialEntries={['/', '/kit']}>
            <Match pattern={'/:district'} render={(props) => {
                  console.log('trigger match');
                  return <Base {...props} main_store={main_store} />
            } />

   describe('click on link', () => {
      beforeEach(() => {
         wrap.find('Link').findWhere(n => n.prop('to') === '/kit/user-1/type-created').simulate('click');

      it('render Profile Bar', () => {
         console.log('current html', wrap.html())

current event log

  1. After mount component recognize that it match current pathname.
  2. Component is rendered first time.
  3. onClick event on is fired

and there is nothing else. In my browser i receive 1 and 2 point again which means that component tree is re-rendered after click on Link. But in my test inv. nothing happend after 3-d point.



answered 1 year ago Paul S #1

The <Link> component expects a left click event (event.button = 0). The default event passed by enzyme does not include this. You can add an event object to your simulate call to properly configure the simulated event.

  .findWhere(n => n.prop('to') === '/kit/user-1/type-created')
  .simulate('click', {
    defaultPrevented: false,
    preventDefault() { this.defaultPrevented = true },
    metaKey: null,
    altKey: null,
    ctrlKey: null,
    shiftKey: null,
    button: 0

comments powered by Disqus