question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

I bet this question has been asked a lot. I have searched for two hours and I am not able to find a solution. There doesn’t seem to be much about preact with jest testing. I looked at the boilerplate and it uses Karma.

Problem

When trying to use Jest with Preact I get the following error:

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

    Cannot find module 'react/lib/ReactComponentTreeHook' from 'ReactDebugTool.js'
      
      at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:169:17)
      at Object.<anonymous> (node_modules/react-test-renderer/lib/ReactDebugTool.js:16:30)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.601s

My setup

I followed the guidelines to setup babel with webpack. My .babelrc is

{
    "plugins": [
        ["transform-react-jsx", { "pragma":"h" }],
        "transform-class-properties"
    ],
    "presets": [
        ["es2015", {
            "modules": false
        }]
    ],
    "env": {
        "test": {
            "plugins": [
                "transform-es2015-modules-commonjs",
                ["transform-react-jsx", { "pragma":"h" }],
                "transform-class-properties"
            ]
        }
    }
}

package.json uses identity-obj-proxy as suggested

 "jest": {
    "moduleNameMapper": {
      "\\.(css)$": "identity-obj-proxy"
    }
  }

And finally my test looks like

import Widget from './index';
import renderer from 'react-test-renderer';


test('Tests for widget to have been rendered', () => {
    const tree = renderer.create(
        <Widget href="http://test.com" target="_blank" data-variation="test"
                innerHTML="<b>test</b> foo bar"/>
    ).toJSON();
    expect(tree).toMatchSnapshot();
});

I am losing my mind. I added react but then I get a bunch of other errors.

Questions

  • Should react-test-renderer work with preact?
  • Is there a better way to do this?

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:18 (7 by maintainers)

github_iconTop GitHub Comments

16reactions
armand1mcommented, Apr 18, 2017

@developit Got it working. It was actually because when you specify a module to jest configuration in package.json, you’re specifying actually a Regexp. When using like this:

{
  "jest": {
    "moduleNameMapper": {
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
      "\\.(css|less|scss)$": "identity-obj-proxy",
      "react": "preact-compat",
      "react-dom": "preact-compat"
    },
    "collectCoverageFrom": [
      "app/**/*.{js,jsx}"
    ],
    "moduleFileExtensions": [
      "js",
      "jsx"
    ],
    "moduleDirectories": [
      "node_modules"
    ]
  }
}

It will not even run a component, because it is looking actually at every component that has “react”, for example, in its name, and replacing their calls to preact-compat.

Got it working using this jest config in my package.json:

{
  "jest": {
    "moduleNameMapper": {
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
      "\\.(css|less|scss)$": "identity-obj-proxy",
      "^react$": "preact-compat",
      "^react-dom$": "preact-compat"
    },
    "collectCoverageFrom": [
      "app/**/*.{js,jsx}"
    ],
    "moduleFileExtensions": [
      "js",
      "jsx"
    ],
    "moduleDirectories": [
      "node_modules"
    ]
  }
}

and this .babelrc:

{
  "sourceMaps": true,
  "presets": [
    ["es2015", {
      "es2015": {
        "loose": true,
        "modules": false
      }
    }],
    "stage-0"
  ],
  "plugins": [
    ["transform-decorators-legacy"],
    ["transform-react-jsx", { "pragma":"h" }]
  ]
}

The slight difference is in the regex for aliasing react and react-dom

15reactions
rsaksidacommented, Mar 16, 2017

Might help someone: I’ve been testing my Preact components with Jest and html-looks-like. It works fine and is pretty easy to set up.

import { h } from 'preact';
import render from 'preact-render-to-string';
import htmlLooksLike from 'html-looks-like';

const Thing = () => (
  <div class="some-class">
    <span>Nope</span>
    <span>Nope</span>
    <span>Yep</span>
  </div>
);

describe('Thing', () => {
  it('has Yep', () => {
    const actual = render(<Thing />);
    const expected = `
      <div>
        {{ ... }}
        <span>Yep</span>
      </div>
    `;

    htmlLooksLike(actual, expected);
  });
});
Read more comments on GitHub >

github_iconTop Results From Across the Web

Testing with Preact Testing Library
The Preact Testing Library is a lightweight wrapper around preact/test-utils . It provides a set of query methods for accessing the rendered DOM...
Read more >
preactjs/jest-preset-preact - GitHub
Jest preset containing all required configuration for writing tests for preact. Features: Transpiles JSX to h(); Aaliases for "react" imports to point to...
Read more >
jest-preset-preact - npm
Jest preset for testing Preact apps. Latest version: 4.0.5, last published: a year ago. Start using jest-preset-preact in your project by ...
Read more >
Writing Unit Test Cases for Preact - Stack Overflow
They're using jest to run the tests. Below is, as a I understand, the relevant parts to get up and running. package.json "jest":...
Read more >
API - Testing Library
import {render} from '@testing-library/preact' ... Keep in mind mainly when using h / Preact. ... const cb = jest.fn() function Counter() {
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found