Search code examples
reactjswebpackbabeljsjestjsraw-loader

Using React stroybook as Jest test


I have a React storybook and what to use it as my test cases

I have a "loader.js" that import all the stories

import sourceBasic from 'raw-loader!./Basics/foo.js?sourceMap';
import Basic from './Basics/foo';

const tree = {
  Basics:[
    {
      title:'Creating and applying a style',
      source:sourceBasic,   element:Basic
    },
    {        ....        }
  ],
  [       ....      ],
  ....
}

export default tree

I use the raw-loader and sourceMap to show the source with the element in storybook

This works great.

My problem is when I try to import with Jest

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

 Cannot find module 'raw-loader!./Basics/foo.js?sourceMap' from 'load.js'

   at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:179:17)
   at Object.<anonymous> (example/stories/load.js:2:34)

The test file

import React from 'react';
import renderer from 'react-test-renderer';
import load from './example/stories/load'

for(const groupName in load ){
  const groupArray = load[groupName];
  describe(groupName, () => {
    for(const item of groupArray ){
      test(item.title, () => {
        const elem = renderer.create(item.element);
        expect(elem.toJSON()).toMatchSnapshot();
      }) // END test
    } // END for
  }) // END describe
} // END for

Thanks for your help

UPDATE

The update and working stroybook as test is implemented on the project react-outline

You can clone it(react-outline), npm install and then npm test to see it in action.

Here is the output on travis :)


Solution

  • If you don't care about the raw-source and want to mock it. You can use the moduleNameMapper under your Jest setting within your package.json.

    This will let you intercept all require/import based on a regex match.

    Add to your package.json:

      ...
      "dependencies": {
         ...
      },
      ...
    
      "jest": {
        "globals": {
          "__TEST__": true
        },
        "moduleNameMapper": {
          "\\.(css|jpg|png)$": "<rootDir>/empty-module.js",
          "^raw-loader": "<rootDir>/empty-module.js"
        },
        "testPathIgnorePatterns": [
          "/node_modules/"
        ],
        "verbose": true
      }
    }