【问题标题】:Getting SyntaxError: Unexpected token export when trying to import a function to test with Mocha获取 SyntaxError:尝试导入函数以使用 Mocha 进行测试时出现意外的令牌导出
【发布时间】:2020-01-08 00:17:35
【问题描述】:

我正在尝试为我拥有的一个功能设置 Mocha 测试,该功能也在 React 应用程序中使用。我目前正在循环运行,要么在尝试导入函数以供 Mocha 使用时出现错误,要么在尝试将函数导入到我的 React 组件中以使用并且开始感到沮丧。我快要放弃了,只是将我想测试的功能直接复制到测试文件中,由于重复,我不想这样做。

我当前的设置如下,导入在我的 React 组件中工作,但在 Mocha 中出现“SyntaxError: Unexpected token export”错误。

这个函数保存在src/function/helpers.js中

export const functionName = () => { 
   // Function logic here
}

React 组件函数导入保存在 src/components/Component.js 中

import {functionName} from '../functions/helpers';

Mocha 测试文件保存在 test/basic-test.js 中

const functionName = require("../src/function/helpers").functionName;

如何将函数导入到这两个文件中而不会收到 React 错误或 Mocha 错误?

【问题讨论】:

    标签: javascript reactjs mocha.js


    【解决方案1】:

    需要连接babel编译es6语法。

    package.json:

    "scripts": {
       "test": "mocha --require @babel/register"
    },
    

    【讨论】:

    • 感谢我在添加 .babelrc 文件后让它工作了!
    猜你喜欢
    • 1970-01-01
    • 2019-07-05
    • 2016-05-04
    • 2021-10-14
    • 2018-04-25
    • 1970-01-01
    • 2016-09-18
    • 2018-12-10
    • 2017-10-20
    相关资源
    最近更新 更多