Jest with coffeescript jsx?

心已入冬 提交于 2019-12-01 03:18:44

I think your second approach was correct, except you did not (I'm guessing here) add react to "unmockedModulePathPatterns" in the jest property of package.json. That is typically the result of the getPooled error in my experience.

The following works for me:

package.json

  // ...
  "jest": {
    "unmockedModulePathPatterns": ["<rootDir>/node_modules/react"],
    "testFileExtensions": [
      "js",
      "coffee"
    ],
    "scriptPreprocessor": "<rootDir>/preprocessor.js"
  }

preprocessor.js

// I found it simpler to use coffee-react,
// since it does the jsx transform and coffeescript compilation 
var coffee = require('coffee-react');

module.exports = {
  process: function(src, path) {
    if (path.match(/\.coffee$/)) {
      return coffee.compile(src, {bare: true});
    }
    return src;
  }
};

This whole process is difficult troubleshoot because errors can happen anywhere during the jsx -> coffee -> js -> jest pipeline and get silently swallowed. I found it most helpful to troubleshoot this by running the transform in a separate file to make sure the jsx -> coffee and coffee -> js happened properly, and then run the jest preprocessor.

I have just published a boiler plate unit test for Jest that works with React & CoffeeScript.

https://github.com/Cotidia/jest-react-coffeescript

The preprocessor needs to be as follows:

var coffee = require('coffee-script');
var ReactTools = require('react-tools');

module.exports = {
  process: function(src, path) {
    // console.log('src', src);
    if (path.match(/\.coffee$/)) {

        // First we compile the coffeescript files to JSX
        compiled_to_js = coffee.compile(src, {bare: true});

        // Then we compile the JSX to React
        compiled_to_react = ReactTools.transform(compiled_to_js)

      return compiled_to_react;
    }
    return src;
  }
};

Based on user2534631's template project, I enhanced to use coffee-react-transform to compile CJSX files.

https://github.com/redice/jest-react-coffeescript

var coffee = require('coffee-script');
var transform = require('coffee-react-transform');

module.exports = {
  process: function(src, path) {
    if (coffee.helpers.isCoffee(path)) {
      compiled_cjx = transform(src);
      compiled_to_react = coffee.compile(compiled_cjx, {bare: true});

      return compiled_to_react;
    }

    return src;
  }
};

So use CJSX syntax to write React components.

render: ->
  <label>
    <input
      type="checkbox"
      checked={this.state.isChecked}
      onChange={this.onChange} />
    {if this.state.isChecked then this.props.labelOn else this.props.labelOff}
  </label>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!