typescript - Jest + Vue - 语法错误 : Unexpected token <

标签 typescript vue.js vuejs2 automated-tests jestjs

我正在尝试使用 ts-Jest/Jest 和 Chai 向使用 TypeScript 编写的 Electron + Vue2 应用程序添加测试。但是,当我尝试运行我编写的简单测试以尝试确保 Jest 正常工作时,我现在遇到了 Jest 的问题,似乎不喜欢我正在导入我正在测试的组件的模板这一事实可以在Error中看到。当我尝试搜索与此相关的内容时,我运气不佳,其中很多指向“意外的 token 导入”,这是我已经解决的问题。

如果有人对我如何让测试不因导入 HTML 而感到 panic 有任何见解或知识,那将是惊人的,因为我很困惑,而且文档似乎没有指出任何有用的东西。

错误:

$ npm run test

> app@1.0.0 test C:\Users\daniel\Desktop\app\app
> jest --detectOpenHandles

FAIL src/app/features/app-window/app-window.component.spec.ts
  ● Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

    Details:

    C:\Users\daniel\Desktop\app\app\src\app\features\app-application-content\app-application-content.component.html:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){<webview-component v-if="src"
                                                                                             ^

    SyntaxError: Unexpected token <

      2 | import Component from 'vue-class-component'
      3 | import { Prop, Watch } from 'vue-property-decorator'
    > 4 | import Template from './app-application-content.component.html'
        | ^
      5 |
      6 | import * as qs from 'qs'
      7 | import { INameValue } from '../../../contracts/Core'

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
      at Object.<anonymous> (src/app/features/app-application-content/app-application-content.component.ts:4:1)
      at Object.<anonymous> (src/app/features/app-content/app-content.component.ts:9:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        12.924s
Ran all test suites.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! app@1.0.0 test: `jest --detectOpenHandles`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the app@1.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\daniel\AppData\Roaming\npm-cache\_logs\2018-11-21T14_25_23_427Z-debug.log

jest.config.js

module.exports = {
  preset: 'ts-jest/presets/js-with-ts',
  testEnvironment: 'node',
  verbose: true,
  moduleDirectories: ['node_modules', 'src'],
  modulePaths: ['<rootDir>/src', '<rootDir>/node_modules'],
  moduleFileExtensions: ['js', 'ts', 'json', 'node'],
  transformIgnorePatterns: ['node_modules/(?!(bootstrap-vue)/)'],
  testPathIgnorePatterns: [
    '/build/',
    '/config/',
    '/data/',
    '/dist/',
    '/node_modules/',
    '/test/',
    '/vendor/'
  ],
  globals: {
    'ts-jest': {
      tsConfig: './src/app/tsconfig.json'
    },
    NODE_ENV: 'test'
  }
}

tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "outDir": "./built/",
    "sourceMap": true,
    "strict": true,
    "moduleResolution": "node",
    "target": "ES2017",
    "experimentalDecorators": true,
    "noImplicitAny": false,
    "emitDecoratorMetadata": true,
    "allowSyntheticDefaultImports": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "esModuleInterop": true,
    "lib": ["es2017", "dom"],
    "include": [
      "**/*",
      "../types/**/*",
      "../../node_modules/bootstrap-vue/**/*",
      "../../node_modules/electron/**/*"
    ]
  }
}

app-window.component.spec.ts

import { expect } from 'chai'
import 'jest'
import { appWindowComponent } from './app-window.component'

const appWindowComponent = new appWindowComponent()

describe('Test: Set Title Function', () => {
  it('should set the variable title to the passed variable', () => {
    const title = 'this is a test'
    appWindowComponent.setTitle(title)
    expect(appWindowComponent.title).to.equal(title)
  })
})

最佳答案

这是一个更新的解决方案:

你需要安装 vue-jest ( https://github.com/vuejs/vue-jest )

npm install -D @vue/vue3-jest

这里是可用的版本及其对应的vue和jest版本

<表类="s-表"> <头> Vue版本 Jest 版 包 <正文> Vue 2 开 Jest <= 26 vue-jest@4 Vue 3 开 Jest <= 26 vue-jest@5 Vue 2 Jest 27 @vue/vue2-jest Vue 3 Jest 27 @vue/vue3-jest

然后,您只需更新您的 jest 配置(例如 jest.config.ts)并添加 transform section

"transform": {
    "^.+\\.vue$": "@vue/vue3-jest"
}

警告:一定要使用正确的 vue-jest 包和 npm install命令并在你的内部 jest.config.ts !

关于typescript - Jest + Vue - 语法错误 : Unexpected token <,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53415363/

相关文章:

javascript - 我可以检测所有图像何时加载,以便将 isLoaded 变量更改为 true 吗?

vue.js - 在vuejs中将事件放在表格行上

javascript - 在 Vue 中,我如何使用 Typescript 语法定义一个使用 prop 作为其初始值的本地数据属性?

javascript - Vue.js - 在输入字段处理程序上动态应用方法

reactjs - 我正在尝试使用useEffect'来更改窗口。我没有收到任何错误,但是没有用。怎么了?如何使其运作?

node.js - 如何在 Sequelize 中使用 TypeScript

typescript - vscode 在 JavaScript 文件中使用类型化定义

javascript - 使用map方法将javascript对象数组转换为其他对象数组

javascript - 在Vue中初始化 'marker-animate-unobtrusive'失败

javascript - 在 vue.js 中按类型对评论进行排序