【问题标题】:Testing React components with Mocha: unexpected token使用 Mocha 测试 React 组件:意外令牌
【发布时间】:2017-04-19 10:00:42
【问题描述】:

我已经充实了我的 React 组件,我想学习如何使用 Mocha + chai 正确测试这些组件。我的package.json(相关)有这些配置:

"scripts": {
    "start": "http-server",
    "build": "watchify main.js -t babelify -o bundle.js",
    "test": "./node_modules/mocha/bin/mocha --compilers js:babel-core/register test/test*.js"
},
"devDependencies": {
    "babel": "^5.6.23",
    "babelify": "^6.1.3",
    "browserify": "^11.0.0",
    "chai": "^3.5.0",
    "jsdom": "^9.8.3",
    "mocha": "^3.2.0",
    "react-addons-test-utils": "^15.4.1"
},
"babel": {
    "presets": [
        "es2015"
    ]
}

我有Skill.js:

import React from 'react';
import _ from 'underscore';

export default class Skills extends React.Component {
    render() {
        return (
            <div>
                <h1>T E S T</h1>
            </div>
        )
    }
}

还有一个名为test 的文件夹中的test.js:

import React from 'react';
import { expect, assert } from 'chai';
import Skills from '../src/components/Skills.js';

我在运行 npm test 时收到意外的令牌错误。

控制台抱怨什么?为什么&lt;div&gt; 标签无效?

【问题讨论】:

  • 可能你需要"presets": ["react", "es2015"]

标签: node.js unit-testing reactjs mocha.js chai


【解决方案1】:

使用前需要安装babel-preset-es2015

npm install --save-dev babel-preset-es2015

【讨论】:

  • 我听取了您的建议并将该依赖项添加到 package.json,但发生了同样的错误。
【解决方案2】:

我遇到了类似的问题,起初我以为我没有import React from 'react';。

接下来发现我没有加--require ./test/test_helper.js

最后但在仍然无法工作之后,我突然意识到我没有重新启动节点。这为我解决了问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 2016-05-04
    • 2017-03-24
    • 2020-10-16
    • 2016-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多