与coffeescript jsx的Jest?
如何使用Jesttesting用CoffeeScript + React jsx编写的React组件?
Jest提供的唯一的CoffeeScript示例使用普通的CoffeeScript,并且不能与CoffeeScript + React JSX一起工作(语法错误达到<
)。
我曾经尝试过
第一次尝试:execSync
// preprocessor.js var execSync = require('exec-sync'); module.exports = { process: function (src, path) { return execSync('browserify -t coffee-reactify ' + path); } };
这工作,但需要太多的时间(虚拟testing12秒)。
然后我试着:
第二次尝试:咖啡反应变换
// preprocessor.js var coffee = require('coffee-script'); var transform = require('coffee-react-transform'); module.exports = { process: function(src, path) { if (path.match(/\.coffee$/)) { return coffee.compile(transform(src), {'bare': true}); } return src; } };
这引发了一个奇怪的错误,如:
TypeError:function(){…}没有方法'getPooled'
“没有办法getPooled”的唯一Google结果就是这个要点 ,它显示了我得到的错误,但是没有提供其他的见解。
第三次尝试
我想我可以使用coffee-reactify ,但是它返回一个stream,它是asynchronous的,而preprocess.js
的process
函数是同步使用的,到目前为止,还没有find同步读取stream的方法。
我能做什么?
我认为你的第二种方法是正确的,除非你没有(我猜这里)添加了对“unmockedModulePathPatterns”package.json的jest
属性的反应。 这是我的经验通常是getPooled
错误的结果。
以下为我工作:
的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; } };
整个过程是很难排除故障的,因为在jsx -> coffee -> js -> jest
pipe道中任何地方都可能发生错误, jsx -> coffee -> js -> jest
悄悄吞下。 我发现通过在单独的文件中运行转换以确保jsx -> coffee
和coffee -> js
正确地发生,然后运行jest预处理程序来排除此问题最有帮助。
我刚刚为Jest发布了一个与React&CoffeeScript一起使用的锅炉板unit testing。
https://github.com/Cotidia/jest-react-coffeescript
预处理器需要如下:
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; } };
基于user2534631的模板项目,我增强了使用coffee-react-transform来编译CJSX文件。
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; } };
所以使用CJSX语法来编写React组件。
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>