开玩笑不预处理我的JSX [英] Jest not preprocessing my JSX

查看:531
本文介绍了开玩笑不预处理我的JSX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在按照笑话教程进行测试组件,并且遇到了我的jsx的预处理问题.我认为错误是由于预处理造成的,错误消息不是很有帮助. Googling显示了较早版本的react/jest的类似错误,该错误通过包含/** @jsx React.DOM */ docblock而得以修复,据我所知,该block是已修复的.

I am following the Jest tutorial to test a react component and am running into preprocessing issues with my jsx. I assume the error is due to preprocessing, the error message is not very helpful. Googling shows similar errors with older versions of react/jest that were fixed by including the /** @jsx React.DOM */ docblock which as far as I can tell was fixed.

运行测试时:

Using Jest CLI v0.8.0, jasmine1
 FAIL  spec/MyComponent_spec.js
Runtime Error
SyntaxError: /Users/asdf/react/stuff-react/spec/MyComponent_spec.js: Unexpected token (13:6)
npm ERR! Test failed.  See above for more details.

有问题的那一行是应该渲染我的组件的那一行:

The line in question is the one that should be rendering my component:

jest.dontMock('../src/MyComponent');

let React = require('react');
let ReactDOM = require('react-dom');
let TestUtils = require('react-addons-test-utils');

const MyComponent = require('../src/MyComponent');

describe('MyComponent', function(){
  it('render', function(){

    var myComponent = TestUtils.renderIntoDocument(
      // This is the line referenced in the test error
      <MyComponent />
    )
    var myComponentNode = ReactDOM.findDOMNode(myComponent);

    expect(myComponentNode.textContent).toEqual('hi');
  });
});

我以为我的package.json负责告诉玩笑预处理该文件?

I thought my package.json was responsible for telling jest to preprocess that file?

 "scripts": {
    "test": "jest"
  },
  "jest": {
    "testDirectoryName": "spec",
    "scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
    "unmockedModulePathPatterns": [
      "<rootDir>/node_modules/react",
      "<rootDir>/node_modules/react-dom",
      "<rootDir>/node_modules/react-addons-test-utils",
      "<rootDir>/node_modules/fbjs"
    ]
  },

我的组件:

import React from 'react';

class MyComponent extends React.Component({
  render () {
    return (
      <div>
        hi
      </div>
    )
  }
});

export default MyComponent;

推荐答案

在项目根目录中使用.bablerc文件为我修复了该问题.

Using a .bablerc file in the project root directory fixed it for me.

开发过程中我没有使用.babelrc文件,因为我在webpack配置文件中定义了预设.但是事实证明,当您使用jest运行单元测试时,jest不了解此预设,因为它不了解webpack.因此,只需添加带有预设的.babelrc文件也可以为您解决问题.

I was not using a .babelrc file while developing because I defined my presets in the webpack configuration file. But it turns out that when you run the unit test with jest, then jest is not aware of this presets as it does not know about webpack. So simply adding a .babelrc file with the presets should solve the issue for you too.

.babelrc的内容:

Contents of .babelrc:

{ "presets": ["es2015", "react"] }

{ "presets": ["es2015", "react"] }

这篇关于开玩笑不预处理我的JSX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆