项目设置
设置我们的测试环境很容易。在以前的Vue.js CLI版本中,我们必须手动执行此操作,但现在它已成为项目生成的标准配置。
通过执行以下操作,确保在计算机上安装了Vue.js CLI:
$ npm install -g @vue/cli
# OR
$ yarn global add @vue/cli
# Ensure you have the appropriate version (3.x.x>) with
$ vue --version
使用以下命令使用CLI创建一个新项目:
$ vue create testing-vue
> Manually select features
> Babel, Linter / Preformatter, Unit Testing
> ESLint (your preference)
> Lint on save
> Jest
> In dedicated config files
$ cd testing-vue
$ code .
$ npm run serve
测试中
现在,我们已经用Jest生成了Vue项目,我们可以打开tests/unit
文件夹。在此文件夹中,我们有一个名为的文件example.spec.js
:
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()).toMatch(msg);
});
});
正如我们内部所引用的package.json
,我们可以通过输入以下内容来运行此单元测试:
$ npm run test:unit
这为我们提供了项目中所有单元测试的结果。
我们可以在其中添加--watch
标志,以使它在创建和编辑新测试时在后台运行。
"scripts": {
"test:unit": "vue-cli-service test:unit --watch"
}
单元测试
在我们的小示例中,我们将创建一个名为的新组件FancyHeading,有一个内部变量
headingStyles和props变量title,color
<template>
<h1 :style="headingStyles">{{title}}</h1>
</template>
<script>
export default {
data() {
return {
headingStyles: {
color: this.color
}
};
},
props: ["title", "color"]
};
</script>
为了对此进行单元测试,我们需要FancyHeading.spec.js
在tests/unit
目录中创建一个相应的文件。
可以将测试套件视为围绕特定模块或功能的测试的测试集合。
让我们看一下Jest和Vue的第一个单元测试。我们将逐行进行解释:
import Vue from 'vue';
import FancyHeading from '@/components/FancyHeading.vue';
function mountComponentWithProps (Component, propsData) {
const Constructor = Vue.extend(Component);
const vm = new Constructor({
propsData
}).$mount();
return vm.$el;
}
describe('FancyHeading.vue', () => {
it('should be the correct color', () => {
const headingData = mountComponentWithProps(FancyHeading, { color: 'red' });
const styleData = headingData.style.getPropertyValue('color');
console.log(styleData)
expect(styleData).toEqual('blue');
});
it('should have the correct title', () => {
const headingData = mountComponentWithProps(FancyHeading, { title: 'Hello, Vue!' });
const titleData = headingData.textContent;
expect(titleData).toEqual('Hello, Vue!');
});
});
- 我们首先导入Vue和要测试的必要组件。
- 我们
describe
过去常常封装围绕FancyHeading
组件的大量单元测试。 - 每个单元测试都是通过
it
函数创建的,首先提供对我们正在测试的内容的准确描述,然后是函数。 - 在第一个断言中
It must have the correct color
,我们使用来将组件安装到新的Vue实例mountComponentWithProps
。 - 然后,我们可以创建一个变量,
styleData
其中包含我们期望从测试中收到的内容。 - 最后,我们通过使用断言这是正确的
expect
。如果使用来检查终端$ npm run test:unit --watch
,则会看到PASS
此单元测试的。
在第二个单元测试中测试标题时,我们采用类似的方法。