我需要在vue-cli-3项目上运行Mocha Test Explorer的babel或其他设置?

我已经通过mocha测试创建了一个vue3 cli项目:

vue create vue_proj_with_mocha_testing 
(accept defaults)
cd vue_proj_with_mocha_testing
vue add unit-mocha

然后在Visual Code中安装mocha Test Explorer扩展,重新启动,将文件夹添加到工作区中,单击文件夹ctrl-shift-p和mocha Test Explorer:“为工作区文件夹启用”。开箱即用的mocha Test Explorer似乎不喜欢vuecli的example.spec.js测试:

import { expect } from 'chai'
import { shallowMount } from '@vue/test-utils'
import HelloWorld from '@/components/HelloWorld.vue'

describe('HelloWorld.vue',() => {
  it('renders props.msg when passed',() => {
    const msg = 'new message'
    const wrapper = shallowMount(HelloWorld,{
      propsData: { msg }
    })
    expect(wrapper.text()).to.include(msg)
  })
})

我将此条目添加到settings.json中,以便Test Explorer找到vue的“ tests”文件夹,该文件夹不同于默认的“ test”文件夹。

"mochaExplorer.files": ["tests/**/*.spec.js"],

然后在测试资源管理器中收到此错误:

import { expect } from 'chai';
^^^^^^

SyntaxError: Cannot use import statement outside a module

这表明我有一些转堆工作要做,而mocha Test Explorer指出了做到这一点的方法是settings.json中的“ mochaTestExplorer”字段,但是我不确定是否需要babel软件包的组合。要在Visual Studio Code的mocha Test Explorer中运行此开箱即用的vue-cli-3测试,应该怎么做?这是我目前的猜测:

"mochaExplorer.require": [
    "@babel/preset-env","@babel/register","@babel/polyfill","@babel/plugin-transform-runtime"
],
chenbin79 回答:我需要在vue-cli-3项目上运行Mocha Test Explorer的babel或其他设置?

首先,在您的@babel/register中添加devDependencies

之后,添加您的Visual Studio代码settings.json

"mochaExplorer.files": "tests/**/*.spec.js","mochaExplorer.env": {
  "NODE_ENV": "test"
},"mochaExplorer.require": [
  "@babel/register"
]

最后,将babel.config.js更改如下:

const presets = [];

if (process.env.NODE_ENV === 'test') presets.push('@babel/preset-env');
else presets.push('@vue/cli-plugin-babel/preset');

module.exports = {
  presets,};
,

恐怕无法实现您想要的-问题是正确设置Babel是不够的。 Vue单个文件组件(.vue)需要由Webpack loader插件Vue Loader处理。

并且没有简单的方法来设置Mocha Test Explorer以使用Webpack,如作者本人在this thread - Support for vue cli projects中指出的那样

因此,我决定将测试分为两组,tests/ui(使用Vue组件的测试)和tests/unit(非ui测试),并使用Fernando描述的设置进行以下修改:

将Mocha Test Explorer配置为仅搜索非ui测试:

"mochaExplorer.files": "tests/unit/**/*.spec.js",

package.json:

"test:unit": "vue-cli-service test:unit tests/unit/**/*.spec.js tests/ui/**/*.spec.js",

...从命令行运行测试时包括两个文件夹

注意:不需要最后一步-修改babel.config.js-没有它,一切都会很好。...

,

在稍微不同的配置下,我为我工作:在.vscode/settings.json

{
    "mochaExplorer.require": "esm"
}

esm也应该位于您的开发依赖项中

本文链接:https://www.f2er.com/3098867.html

大家都在问