Search code examples
meteorreactjsflow-routerenzymemantrajs

How to pass FlowRouter context in testing React components


I am testing a react component that have 5 links on it. Each link becomes active based on the current route. I am using Meteor with Mantra and enzyme for testing these components.

Footer component:

import React from 'react';

class Footer extends React.Component{

    render(){
       let route = FlowRouter.current().route.name;

       return(
          <a className={route == 'hub page' ? 'some-class active' : 'some-class'}> . . . (x5)
       )
    }

}

Testing

describe {shallow} from 'enzyme';
import Footer from '../core/components/footer';

describe('footer',() => {
    it('should have 5 links', () => {
       const fooWrapper = shallow(<Footer/>);
       expect(fooWrapper.find('a')).to.have.length(5);
    })
})

But when I run npm test, it says that FlowRouter is not defined. How do I pass the FlowRouter context to a react component in testing? Thanks in advance


Solution

  • First of all, to comply with Mantra specifications, you should rewrite your Footer component like this:

    import React from 'react';
    
    const Footer = ({ route }) => (
      <a className={
        route == 'hub page' ? 'some-class active' : 'some-class'
      }> ... (x5)
    );
    
    export default footer;
    

    Now to test your Footer, you don't now need FlowRouter at all:

    import { shallow } from 'enzyme';
    import Footer from '../core/components/footer';
    
    describe('footer', () => {
      it('should have 5 links', () => {
        const fooWrapper = shallow(<Footer route={'foo'}/>);
        expect(fooWrapper.find('a')).to.have.length(5);
      })
    })
    

    To make the footer reactively re-render as FlowRouter.current() changes, you need to create a Mantra container to wrap it in. To test the container, you can mock FlowRouter like this:

    it('should do something', () => {
      const FlowRouter = { current: () => ({ route: { name: 'foo' } }) };
    
      const container = footerContainer({ FlowRouter }, otherArguments);
      ...
    })
    

    Since Mantra uses the mocha package directly from NPM instead of the practicalmeteor:mocha or similar Meteor package to run tests, you cannot (to my knowledge) load Meteor packages such as kadira:flow-router in your tests.