Typescript Jest测试中的ol-ext中的“ SyntaxError:意外标识符”

时间:2019-08-15 17:16:12

标签: javascript typescript jestjs openlayers

我在我的应用程序中使用了openlayers扩展库ol-ext。当我运行应用程序时,它运行良好,但是尝试运行测试时出现问题。当运行测试并尝试创建对象时,我得到以下信息:

({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import ol_ext_inherits from '../util/ext'
                                                                                                    ^^^^^^^^^^^^^^^
    SyntaxError: Unexpected identifier



      at ScriptTransformer._transformAndBuildScript (../../../node_modules/@jest/transform/build/ScriptTransformer.js:471:17)
      at ScriptTransformer.transform (../../../node_modules/@jest/transform/build/ScriptTransformer.js:513:25)
      at Object.<anonymous> (src/private/geomap-ol/interaction-edit.ts:1429:41)

我尝试在jest配置中修改我的“ transformIgnorePatterns”以包括ol-ext,但这导致了openlayers无法解决的问题:

当前jestconfig.json:

{
    "transform": {
        "^.+\\.tsx?$": "ts-jest",
        "^.+\\.jsx?$": "babel-jest",
        "^.+\\.svg$": "jest-svg-transformer",
        "^.+\\.xml$": "jest-raw-loader"
    },
    "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
    "moduleFileExtensions": ["ts", "tsx", "js", "jsx", "json", "node"],
    "collectCoverage": true,
    "collectCoverageFrom": ["src/**/*.{js,ts,jsx,tsx}"],
    "coveragePathIgnorePatterns": ["<rootDir>/src/index.ts", "<rootDir>/node_modules/"],
    "transformIgnorePatterns": ["node_modules/(?!(ol)/)"],
    "testEnvironment": "jest-environment-jsdom-fifteen",
    "setupFiles": ["jest-canvas-mock"]
}

尝试了jestconfig.json:

{
    ...
    "transformIgnorePatterns": ["node_modules/(?!(ol|ol\\-ext)/)"],
    ...
}

"transformIgnorePatterns": ["node_modules/(?!(ol|ol\\-ext)/)", "node_modules/(?!(ol\\-ext)/)"],

这两个版本都导致ol库也停止被忽略。

babel.config.js:

module.exports = {
    presets: [
        [
            '@babel/preset-env',
            {
                targets: {
                    node: 'current',
                },
            },
        ],
    ],
};

我希望ol-ext库也可以在测试期间使用,这样我就不会有大量未经测试的代码。

1 个答案:

答案 0 :(得分:0)

jest.config.js

module.exports = {
  transform: {
    '^.+\\.ts$': 'ts-jest'
  },
  moduleFileExtensions: [
    'js',
    'ts'
  ],
  testMatch: [
    '**/test/**/*.test.(ts|js)'
  ],
  testEnvironment: 'node'
}

package.json

{
  // ...
  "scripts": {
    "test": "jest --verbose",
    "test-watch": "jest --verbose --watchAll",
    // ...
  }
  // ...
}