Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest tests with enzyme and connect() giving `import connectAdvanced from '../components/connectAdvanced';`

I am having troubles running a simple jest/enzyme test when using connect on a component. I have tried to use dive() as suggested here: Testing a Redux-connected component using Enzyme. But still the error is exactly the same.

I would like to be able to test components that are wrapped with shallow and not this error (obviously)

Console Failure

 FAIL  src/containers/Home/index.test.js
  ● Test suite failed to run

    /var/www/cloud/websites/www/node_modules/react-redux/es/connect/connect.js:5
    import connectAdvanced from '../components/connectAdvanced';
           ^^^^^^^^^^^^^^^

    SyntaxError: Unexpected identifier

      at new Script (vm.js:74:7)
      at Object.<anonymous> (src/components/shared/buttons/index.js:3:16)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.482s
Ran all test suites related to changed files.

Watch Usage: Press w to show more.

home.index.js

import React, { PureComponent, Fragment } from 'react';
import ButtonUI from '../../components/shared/buttons';

export default class Home extends PureComponent {
  render() {
    return (
      <ButtonUI galabel="testLabel" gaaction="testAction">
        Fire GA Test
      </ButtonUI>
    );
  }
}

components/shared/buttons/index.js

import React, { PureComponent } from 'react';
import connect from 'react-redux/es/connect/connect';

class ButtonUI extends PureComponent {
  render() {
    return (
      <button>
        {this.props.children}
      </button>
    );
  }
}

export default connect()(ButtonUI);

home/index.test.js

import React, { PureComponent } from 'react';
import Home from './index.js';
import { shallow, mount, render } from 'enzyme';

const wrapper = shallow(<Home />).dive();

describe('Home Page Can Render', () => {
  it('Contains a header', () => {
    expect(wrapper.find('h5')).to.have.lengthOf(1)
  });
});

Package.json

"react-router": "^4.3.1",
"react-router-dom": "^4.3.1",
"connected-react-router": "^4.4.1",
"enzyme": "^3.6.0",
"enzyme-adapter-react-16": "^1.5.0",
"enzyme-to-json": "^3.3.4",
"react-scripts": "^2.1.1",
like image 274
Jamie Hutber Avatar asked Nov 07 '18 15:11

Jamie Hutber


1 Answers

connect is imported as an es6 module and NodeJS runtime doesn't know what to do with it.

import connect from 'react-redux/es/connect/connect';

Usually library authors have their library transpiled in commonjs for interoperability with multiple environments and provide that as the entry point for their module

While you can update your bundler configuration to also transpile module imports from the node_modules folder, I suggest to use the module entrypoint instead as it's more straightforward that way.

import { connect } from "react-redux";
like image 96
Oluwafemi Sule Avatar answered Oct 23 '22 03:10

Oluwafemi Sule