我想使用 ava
对我的 Vue
组件进行单元测试。现在我有一个非常简单的设置:
package.json
{
"name": "vue-testing",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"babel": {
"presets": [
"es2015"
]
},
"ava": {
"require": [
"babel-register",
"./test/helpers/setup-browser-env.js"
]
},
"devDependencies": {
"ava": "^0.18.1",
"babel-preset-es2015": "^6.24.1",
"babel-register": "^6.22.0",
"browser-env": "^2.0.21"
},
"dependencies": {
"vue": "^2.1.10"
}
}
./test/helpers/setup-browser-env.js
import browserEnv from 'browser-env';
browserEnv();
./test/Notification.js
import Vue from 'vue/dist/vue.js';
import test from 'ava';
import Notification from '../src/Notification';
let vm;
test.beforeEach(t => {
let N = Vue.extend(Notification);
vm = new N({ propsData: {
message: 'Foobar'
}}).$mount();
});
test('that it renders a notification', t => {
t.is(vm.$el.textContent, 'FOOBAR');
});
src/Notification.js
export default {
template: '<div><h1>{{ notification }}</h1></div>',
props: ['message'],
computed: {
notification() {
return this.message.toUpperCase();
}
}
};
当我运行 ava
时,一切都按预期工作:1 passed
。
如果我可以使用以下组件语法,我会更高兴:
./src/Notification.vue
<template>
<div>
<h1>{{ notification }}</h1>
</div>
</template>
<script>
export default {
props: ['message'],
computed: {
notification() {
return this.message.toUpperCase();
}
}
}
</script>
但是 ava
将返回以下错误:
> 1 | <template>
| ^
2 | <div>
3 | <h1>{{ notification }}</h1>
4 | </div>
我不知道该怎么做,如果有任何帮助,我们将不胜感激!
最佳答案
问题
在运行之前,您需要将 .vue 文件编译成 JavaScript。
解决方案
您可以根据需要使用 vue-node 在模块上运行 vue-loader .
运行 npm install --save-dev vue-node
,将 vue-node 添加到您的项目中
在您的/helpers 目录中,创建一个 setup.js 文件
添加以下内容:
const hook = require('vue-node');
const { join } = require('path');
// Pass an absolute path to your webpack configuration to the hook function.
hook(join(__dirname, './path/to/webpack.config.js'));
./path/to/webpack.config.js
是相对于您的项目的带有 vue-loader
的 webpack 配置的路径。
在package.json中,添加
"ava": {
"require": [
"./test/helpers/setup.js"
]
},
作为属性(property)。
您可以在此处查看工作示例存储库 - https://github.com/eddyerburgh/avoriaz-ava-example
备选方案
This thread展示了几种使用 ava 进行测试的方法。
关于javascript - 如何测试单文件 Vue 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43678826/