【问题标题】:SyntaxError: Unexpected token { when loading node module during jest testSyntaxError: Unexpected token { 在开玩笑测试期间加载节点模块时
【发布时间】:2017-06-13 06:06:07
【问题描述】:

我正在运行一个依赖于“antd”节点模块的玩笑测试

似乎无法正确解析 atnd 模块内的 css 文件。 我该如何解决这个问题?

当我运行它时,它会失败如下:

C:\path\to\project\node_modules\antd\lib\style\index.css:10
html {
     ^
SyntaxError: Unexpected token {

  at transformAndBuildScript (node_modules\jest-cli\node_modules\jest-runtime\build\transform.js:316:10)
  at Object.<anonymous> (node_modules\antd\lib\switch\style\css.js:3:1)

我的babelrc如下:

{
  "presets": [
    "react",
    "es2015-loose",
    "stage-0"
  ],
  "plugins": [
    "babel-root-slash-import",
    "transform-decorators-legacy",
    "react-hot-loader/babel",
    "transform-runtime",
    ["import", [{"libraryName": "antd", "style" : true}]]
  ],
  "compact": true,
  "ignore": [
    "/node_modules/(?!react-number-input)"
  ]
}

jest.json

{
  "setupTestFrameworkScriptFile": "<rootDir>/jasmine-setup-env.js",
  "bail": false,
  "collectCoverage": true,
  "collectCoverageFrom": [
    "**/src/**/*.js",
    "!**/node_modules/**"
  ],
  "coverageDirectory": "coverage",
  "coveragePathIgnorePatterns": [
    "<rootDir>/node_modules"
  ],
  "coverageThreshold": {
    "global": {
      "branches": 20,
      "functions": 15,
      "lines": 20,
      "statements": 20
    }
  },
  "globals": {
    "SOURCEMAP": true
  },
  "modulePaths": [
    "<rootDir>/src",
    "<rootDir>/sass",
    "<rootDir>/public",
    "<rootDir>/node_modules",
    "<rootDir>/config"
  ],
  "resetModules": true,
  "testPathDirs": [
    "<rootDir>/test/util"
  ],
  "testRegex": "(/test/.*|\\.(test|spec))\\.(js|jsx)$",
  "verbose": false,
  "unmockedModulePathPatterns": [
    "<rootDir>/node_modules/"
  ]
}

js 文件 jasmine-setup-env 只添加 jasmine 报告器并打开 jest-enzyme

我的 webpack 配置包含以下内容:

const webpack = require('webpack');
var path = require('path');

module.exports = {
    entry: [
        './src/main'
    ],
    output: {
        path: './public',
        filename: 'bundle.js'
    },
    module: {
        // in loaders you set the plugins to use when loading specific fle extensions
        loaders: [
            {
                // any js files should be loaded by babel
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel',
                query: {
                    "presets": ["es2015", "stage-0", "react"],
                    "plugins": ["transform-decorators-legacy"]
                },
                include: path.join(__dirname, 'src')
            },
            {
                // json files use the json loader
                test: /\.json$/, loader: 'json'
            },
            {
                // any static files are loaded directly as a file
                test: /\.(ico|gif|png|jpg|jpeg|svg|woff|ttf|eot|webp)$/,
                loaders: ["file?context=public&name=/[path][name].[ext]"],
                exclude: /node_modules/
            },
            {
                // css fles are loaded using the css loader
                test: /\.css$/,
                loader: 'style!css!'
            }
        ]
    },
    // in here we specify the configuration for when we require or import specific modules
    resolve: {
        // we accept any file that is either as-is, using a .js or .json extension
        extensions: ['', '.js', '.json'],
        // these directories are the roots in which we scan for files given
        modulesDirectories: [
            "src",
            "sass",
            "public",
            "node_modules",
            "config"
        ],
        // these shims are needed for bunyan
        alias: {
            'dtrace-provider': path.resolve('empty-shim.js'),
            'safe-json-stringify': path.resolve('empty-shim.js'),
            "mv": path.resolve('empty-shim.js'),
            'source-map-support': path.resolve('empty-shim.js')
        }
    },
    plugins: [
        // in the provide plugin we specify which classes will be automatically replaced with requires by webpack
        // eg: Any reference to React will be replaced with require('react') without any imports required
        new webpack.ProvidePlugin({
            'React': 'react',
            '$': 'jquery',
            'jQuery' : 'jquery'
        })
    ],
    node: {
        fs: 'empty' // we are mocking node's fs module to be empty
    }
};

【问题讨论】:

  • 看起来像是将你的 css 加载为 javascript!
  • 测试用例在 webpack 配置中应该是正确的

标签: javascript node.js reactjs webpack jestjs


【解决方案1】:

如果您在 try/catch 块中的 jest-cli 中 index.js 的第 227 行或类似内容中获得此信息,请检查您的 node.js 版本。我的很旧(8.17.0)产生了这个错误,使用更新版本的节点为我解决了这个问题。

【讨论】:

    【解决方案2】:

    在我的例子中,模拟出 css 内容就足够了

    我在这里使用了 identity-obj-proxy:https://jestjs.io/docs/webpack

    示例 package.json :

    {
      "jest": {
        "moduleNameMapper": {
          "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
          "\\.(css|less)$": "identity-obj-proxy"
        }
      }
    }
    

    (因链接失效而编辑)

    【讨论】:

    • 如果您能包含更多细节,那就太好了。你是怎么嘲笑它的?代码示例?另外,链接失效了
    • 链接现在也被破坏了。最好的猜测是this 是正确的链接
    猜你喜欢
    • 1970-01-01
    • 2020-01-24
    • 2019-05-17
    • 2019-06-24
    • 2018-04-05
    • 2018-03-29
    • 1970-01-01
    • 2020-11-21
    • 1970-01-01
    相关资源
    最近更新 更多