使用 Jest 测试 Vue

测试 Vue.js 应用程序的重要性不应该被低估,并且 Jest使这一点比以往任何时候都更容易。

由于我们处于 Vue.js 环境中,我们还将使用 vue-test-utils来方便与原生 Vue 元素的接口。

项目设置

在以前的 Vue.js CLI 版本中,我们不得不手动设置我们的测试环境,但现在它是项目生成时的标准。

確保您已在您的電腦上安裝 Vue.js CLI:

1$ npm install -g @vue/cli
2# OR
3$ yarn global add @vue/cli
4
5# Ensure you have the appropriate version (3.x.x>) with
6$ vue --version

使用 CLI 创建一个新的项目如下:

 1$ vue create testing-vue
 2
 3> Manually select features
 4> Babel, Linter / Preformatter, Unit Testing
 5> ESLint (your preference)
 6> Lint on save
 7> Jest
 8> In dedicated config files
 9
10$ cd testing-vue
11$ code .
12$ npm run serve

测试

现在我们已经用 Jest 生成了 Vue 项目,我们可以导航到测试/单元文件夹。

 1import { shallowMount } from "@vue/test-utils";
 2import HelloWorld from "@/components/HelloWorld.vue";
 3
 4describe("HelloWorld.vue", () => {
 5  it("renders props.msg when passed", () => {
 6    const msg = "new message";
 7    const wrapper = shallowMount(HelloWorld, {
 8      propsData: { msg }
 9    });
10    expect(wrapper.text()).toMatch(msg);
11  });
12});

正如我们在package.json中所提到的,我们可以通过键入执行此单元测试:

1$ npm run test:unit

这给了我们项目内的所有单元测试的结果,目前一切都按预期顺利进行。

我们可以添加观看旗,以便在我们创建和编辑新测试时,在后台运行。

1"scripts": {
2  "test:unit": "vue-cli-service test:unit --watch"
3}

单位测试

在我们的小示例中,我们将创建一个名为FancyHeading的新组件,这将代表一个标题,可以使用附件来自定义一个标题颜色

 1<template>
 2  <h1 :style="headingStyles">{{title}}</h1>
 3</template>
 4
 5<script>
 6export default {
 7  data() {
 8    return {
 9      headingStyles: {
10        color: this.color
11      }
12    };
13  },
14  props: ["title", "color"]
15};
16</script>

为了单元测试,我们需要在测试/单元目录中创建相应的FancyHeading.spec.js文件。

测试套件可以被认为是围绕测试特定模块或功能的测试集合。

让我们看看我们使用 Jest 和 Vue 进行的第一个单元测试,我们将沿线调查:

 1import Vue from 'vue';
 2import FancyHeading from '@/components/FancyHeading.vue';
 3
 4function mountComponentWithProps (Component, propsData) {
 5  const Constructor = Vue.extend(Component);
 6  const vm = new Constructor({
 7    propsData
 8  }).$mount();
 9
10  return vm.$el;
11}
12
13describe('FancyHeading.vue', () => {
14  it('should be the correct color', () => {
15    const headingData = mountComponentWithProps(FancyHeading, { color: 'red' });
16    const styleData = headingData.style.getPropertyValue('color');
17
18    console.log(styleData)
19
20    expect(styleData).toEqual('blue');
21  });
22
23  it('should have the correct title', () => {
24    const headingData = mountComponentWithProps(FancyHeading, { title: 'Hello, Vue!' });
25    const titleData = headingData.textContent;
26
27    expect(titleData).toEqual('Hello, Vue!');
28  });
29});

我们开始通过导入Vue和我们想要测试的必要组件 2.我们使用描述来包装我们FancyHeading组件周围的众多单元测试 3.每个单元测试都是用It函数创建的,首先提供我们正在测试的确切描述,然后是函数 4.在我们的第一个说法中,它必须有正确的颜色,我们将我们的组件安装到一个新的Vue实例中,使用mountComponentWithProps 5.我们然后可以创建一个变量,风格数据,其中包含我们期望从我们的测试中获得的内容 6.最后,我们声称这是通过使用期望

我们在第二个单元测试中测试我们标题的标题时采取类似的方法。

有关使用 Vue.js 进行测试的更多信息,请参阅 Karma 和 Mocha 指南Joshua Bemenderfer

Published At
Categories with 技术
Tagged with
comments powered by Disqus