jest + enzyme: TypeError: Cannot read property 'htmlparser2' of undefined

Viewed 886

I'm using jest and enzyme to build this test, but I'm having this error when I build it.

This is the test

import React from 'react';
import { shallow, render } from 'enzyme';

import Title from './../';

describe('Title', () => {
  it('should render correctly', () => {
    const TitleDOM = render(<Title />);
    expect(TitleDOM).toBeDefined();
  });
});

This is the error enter image description here

Versions:
"react": "^16.0.0",
"jest": "^21.2.1",
"enzyme": "^3.2.0"

I appreciate if someone can help me.

2 Answers

I was having similar issue with electron native components and the solution that worked for me was isolating those components to a separate file.

You could just separate the usage of the htmlparser2 to a function outside the component in a helper file.

Hit this issue myself today, turns out cheerio (a dependency of enzyme) introduced breaking changes in their 1.x version, and enzyme doesn't appear to correctly pin the version to avoid this.

You can see the related cheerio issues here:

Essentially, they're moving away from htmlparser2 by default, but there is a way to continue it's use.

I opened an enzyme issue about this here (which details where you could make the required changes in enzyme if required):

A workaround in the meantime would be to coerce cheerio's version resolution in your package.json, which can be done by adding a resolutions entry like the following:

{
  // ..snip: other package.json things..
  "dependencies": {
    "enzyme": "^3.9.0",
    // ..snip: all of your other dependencies..
  },
  "resolutions": {
    "cheerio": ">= 0.22.0 < 1.0.0"
  }
}

This appears to be a yarn specific feature, which you can read more about at:

If you use npm, there appears to be an equivalent package called npm-force-resolutions (though I haven't used it personally):

Related