How to use jest with webpack?

前端 未结 12 2580
抹茶落季
抹茶落季 2020-12-08 06:00

I use webpack to develop a React component. Here is a simple version of it:

\'use strict\';

require(\'./MyComponent.less\');

var React = require(\'react\')         


        
12条回答
  •  隐瞒了意图╮
    2020-12-08 07:03

    I have experienced similar issue with such pattern

    import React, { PropTypes, Component } from 'react';
    import styles from './ContactPage.css';
    import withStyles from '../../decorators/withStyles';
    
    @withStyles(styles)
    class ContactPage extends Component {
    

    see example at https://github.com/kriasoft/react-starter-kit/blob/9204f2661ebee15dcb0b2feed4ae1d2137a8d213/src/components/ContactPage/ContactPage.js#L4-L7

    For running Jest I has 2 problems:

    • import of .css
    • applying decorator @withStyles (TypeError: <...> (0 , _appDecoratorsWithStyles2.default)(...) is not a function)

    First one was solved by mocking .css itself in script preprocessor.

    Second one was solved by excluding decorators from automocking using unmockedModulePathPatterns

    module.exports = {
      process: function (src, filename) {
    
        ...
    
        if (filename.match(/\.css$/)) src = '';
    
        ...
    
        babel.transform(src, ...
      }
    }
    

    example based on https://github.com/babel/babel-jest/blob/77a24a71ae2291af64f51a237b2a9146fa38b136/index.js

    Note also: when you working with jest preprocessor you should clean cache:

    $ rm node_modules/jest-cli/.haste_cache -r
    

提交回复
热议问题