wisetc / practice

Practice conclusion
5 stars 0 forks source link

vue组件单元测试 #8

Open wisetc opened 6 years ago

wisetc commented 6 years ago

报错SyntaxError: Unexpected token import

如下图,报错原因是jest是在node的环境中运行,需要将es的模块语法转化成commonjs的模块语法。

解决办法是安装babel-plugin-transform-es2015-modules-commonjs插件,配置.babelrc

 {
  "presets": [
    ["env", {
      "modules": false,
      "targets": {
        "browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
      }
    }],
    "stage-2", "flow"
  ],
  "plugins": [
    "transform-runtime"
  ],
  "env": {
    "test": {
      "presets": [
        ["env", {
          "targets" : {
            "node": "8"
          }
        }], "stage-2", "flow"
      ],
      "plugins": ["transform-es2015-modules-commonjs"]
    }
  }
}

如下图

参考:https://babeljs.io/docs/en/babel-plugin-transform-es2015-modules-commonjs/#top

wisetc commented 6 years ago

相关配置,在package.json的配置jest相关配置

{
  "scripts": {
    "test": "jest --no-cache"
  },
  "devDependencies": {
    "@vue/test-utils": "^1.0.0-beta.18",
    "babel-core": "^6.26.3",
    "babel-jest": "^23.0.1",
    "babel-plugin-transform-es2015-modules-commonjs": "^6.26.2",
    "babel-preset-env": "^1.7.0",
    "babel-preset-es2017": "^6.24.1",
    "babel-preset-flow": "^6.23.0",
    "babel-preset-stage-2": "^6.24.1",
    "jest": "^23.1.0",
    "vue-jest": "^2.6.0",
    "vue-template-compiler": "^2.5.16"
  },
  "dependencies": {
    "vue": "^2.5.16"
  },
  "jest": {
    "moduleFileExtensions": [
      "js",
      "jsx",
      "vue",
      "node"
    ],
    "transform": {
      ".+\\.vue": "vue-jest",
      ".+\\.jsx?": "babel-jest"
    },
    "moduleNameMapper": {
      "@/(.*)$": "<rootDir>/src/$1"
    }
  }
}
wisetc commented 6 years ago

示例vue组件测试文件

import {mount, createLocalVue} from '@vue/test-utils'
import DateRange from '@/components/forms/TrusteeshipForm/DateRange'
import ElementUI from 'element-ui'
import moment from 'moment'

const localVue = createLocalVue()
localVue.use(ElementUI)

describe('DateRange.vue', () => {
  it('one year with cycle onemonth should have 12 items', () => {
    const wrapper = mount(DateRange, {
      localVue,
      mocks: {
        moment
      },
      propsData: {
        cycle: 'ONEMON',
        startTime: new Date('2018-06-17'),
        endTime: new Date('2019-06-16'),
        rental: 500
      }
    })
    expect(wrapper.vm.reqChargInputLogBeanList.length).toBe(12)
  })
})
wisetc commented 6 years ago

文档链接

Testing Single File Components with Jest