编写vue.js用什么软件

Vue.js is a JavaScript framework which is useful for building the front-end of web applications, particularly when creating complex features. For every project, it's necessary to go through everything in our applications and check that it all works as expected. However, for large projects, it quickly becomes tedious to check every feature after every new update. For this reason, we can create automated tests which can run all the time and give us reassurance that our code works. In this tutorial, we will create a few simple unit tests for VueJS which show how to get started.

Vue.js是一个JavaScript框架,可用于构建Web应用程序的前端,特别是在创建复杂功能时。 对于每个项目,有必要遍历我们应用程序中的所有内容,并检查它们是否按预期工作。 但是,对于大型项目,在每次新更新后检查每个功能很快变得很繁琐。 因此,我们可以创建可以一直运行的自动化测试,并向我们保证代码可以正常工作。 在本教程中,我们将为VueJS创建一些简单的单元测试,以展示如何入门。

To have something to test, we will be making a basic to-do list component. We'll test that the list gets displayed correctly and also that the user can add new items to the to-do list. Hopefully, by the end of this tutorial, you'll be able to write tests which check what your component outputs to the user and which simulate user actions by interacting with the HTML (for example by clicking a button).

为了进行测试,我们将制作一个基本的待办事项列表组件。 我们将测试列表是否正确显示,并且用户可以将新项目添加到待办事项列表中。 希望在本教程结束时,您将能够编写测试,以检查组件向用户输出的内容以及通过与HTML交互(例如,单击按钮)来模拟用户操作的过程。

Here is my Github repo with all the code in this post.

这是我的Github存储库,其中包含本文中的所有代码。

建立 ( Set up )

设置JavaScript项目可能是一个复杂的过程。 有太多需要选择的库,所有库的用途都略有不同。 幸运的是,对于VueJS,我们有[vue-cli](https://github/vuejs/vue-cli),它为我们设置了一切! 您需要先安装npm,然后才能运行以下命令:
npm install -g vue-cli
vue init webpack project-name

At this stage, you'll be prompted with a few questions. Most of them are straightforward and you can choose the default option, the only requirement is that you answer YES to including vue-router and YES to setting up unit tests with Karma and Mocha. Then install the dependencies:

在此阶段,系统将提示您一些问题。 它们中的大多数都是简单明了的,您可以选择默认选项,唯一的要求是您对包括vue-router回答是,对与Karma和Mocha一起设置单元测试回答是。 然后安装依赖项:

cd project-name
npm install

This final command will start up your browser and take you to localhost where your application will be running:

最后一条命令将启动浏览器,并带您到运行应用程序的本地主机:

npm run dev

Here is a (very) brief overview of some of the key dependencies that vue-cli has set up for us, including the version which was installed for my own project.

这是vue-cli为我们建立的一些关键依赖项的(非常)简要概述,包括为我自己的项目安装的版本。

依存关系 (Dependencies)

** Webpack(v2.3)**是一个捆绑器,它将各种JavaScript,CSS,HTML(和其他)文件组合在一起,使它们可以由客户端处理。
**Babel (v6.22)** is a compiler for ECMAScript 6 to ECMAScript 5. These are different JavaScript standards and currently browsers are not able to understand all of ECMAScript 6 and so it needs to be converted.
** Babel(v6.22)**是ECMAScript 6到ECMAScript 5的编译器。这些是不同JavaScript标准,当前浏览器无法理解所有ECMAScript 6,因此需要对其进行转换。

测试依赖 (Testing Dependencies)

** Karma(v1.4)**是一个测试运行程序,它生成一个Web服务器,其中包含项目的应用程序代码,并针对该服务器执行测试。
**Mocha (v3.2)** is a testing framework for JavaScript.
Mocha(v3.2)**是JavaScript的测试框架。
**Chai (v3.5)** is an assertion library which can be used with Mocha.
** Chai(v3.5)**是可以与Mocha一起使用的断言库。



In your project, you should find the following folders: build, config, node_modules, src, static and test. The only ones which are important for this tutorial are src, which will hold our application code, and test.



在您的项目中,您应该找到以下文件夹: buildconfignode_modulessrcstatictestsrc对本教程来说很重要,它将保存我们的应用程序代码和test

我的第一个测试 ( My First Test )

从一开始就相当基本的事情开始总是好事。 我们将从创建简单的列表组件开始。 在src / components文件夹中创建一个名为List.vue的新文件,并将以下代码放入其中:
<template>
  <div>
    <h1>My To Do List</h1>
    </br>
    <!--displays list -->
    <ul>
      <li v-for="item in listItems">{{ item }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'list',
  data () {
    return {
      listItems: ['buy food', 'play games', 'sleep'],
    }
  }
}
</script>

In the component, the list items are stored in an array (listItems) in the component data. This data is then accessible to the template where it is looped over in a foreach loop (v-for), and displayed on the page.

在组件中,列表项存储在组件数据中的数组( listItems )中。 然后,模板可以访问此数据,在模板中将其以foreach循环( v-for )进行循环,并显示在页面上。

Since it's more fun if we can see our list, we can create a new route to display our component. Go into src/router/index.js and add a route, and your code should look something like this:

如果可以看到列表,这会更加有趣,所以我们可以创建一条新路径来显示我们的组件。 进入src/router/index.js并添加一条路由,您的代码应如下所示:

import Vue from 'vue'
import Router from 'vue-router'
import Hello from '@/components/Hello'
import List from '@/components/List'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Hello',
      component: Hello
    },
    {
      path: '/to-do',
      name: 'ToDo',
      component: List
    },
  ]
})

Now if you navigate to localhost:8080/#/to-do, you will see your list!

现在,如果您导航到localhost:8080/#/to-do ,您将看到您的列表!

First we want to test if the data is displayed correctly. Inside test/unit/specs, create a new file List.spec.js and put the following code:

首先,我们要测试数据是否正确显示。 在test/unit/specs内部,创建一个新文件List.spec.js并添加以下代码:

import List from '@/components/List';
import Vue from 'vue';

describe('List.vue', () => {

  it('displays items from the list', () => {
      // our test goes here
  })
})

In this file, we are describing the List.vue component and we have a single empty test which will check that it (the component) displays items from the list. This is the basic file structure for Mocha tests.

在此文件中,我们描述 List.vue组件,并且有一个空测试将检查 (该组件)是否显示列表中的项目。 这是Mocha测试的基本文件结构。

Inside our test, we first need to set up the Vue component. Copy the code below and put it under the comment 'our test goes here':

在测试中,我们首先需要设置Vue组件。 复制下面的代码,并将其放在“我们的测试在这里”的注释下:

// build component
const Constructor = Vue.extend(List);
const ListComponent = new Constructor().$mount();

We extend Vue and then mount our component. It is important to mount the component as this is the bit that renders the HTML in our template. This essentially means that the HTML gets built and the variables in our template (e.g. {{ item }}) get filled with data, enabling us to later have access to the HTML (via $el).

我们扩展Vue,然后安装我们的组件。 安装组件很重要,因为这是在模板中呈现HTML的位。 从本质上讲,这意味着将构建HTML,并在模板中的变量(例如{{item}})中填充数据,从而使我们能够稍后(通过$ el)访问HTML。

With our component ready, we can write our first assertion. In this example we are using the 'expect' style, which is provided by Chai assertion library, along with 'should' and 'assert'. Put the following code after mounting the component:

准备好组件之后,我们可以编写第一个断言。 在此示例中,我们使用Chai断言库提供的“期望”样式以及“应该”和“声明”样式。 安装组件后,输入以下代码:

// assert that component text contains items from the list
expect(ListComponent.$el.textContent).to.contain('play games');

As I mentioned before, we can get the component's HTML using ListComponent.$el, and to access only the inner HTML (i.e. the text), we have ListComponent.$el.textContent. The assertion is checking that the text contains one of the list items which is set in the component's data.

如前所述,我们可以使用ListComponent.$el获取组件HTML,并且仅访问内部HTML(即文本),我们拥有ListComponent.$el.textContent 。 该断言正在检查文本是否包含在组件数据中设置的列表项之一。

To check that everything is working as it should be, we can run the tests! With the vue-cli project, we can simply type npm run unit, which is an alias for cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run (much more memorable!)

要检查一切是否正常运行,我们可以运行测试! 在vue-cli项目中,我们可以简单地键入npm run unit ,这是cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run的别名cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run (更令人难忘!)

npm run unit

If all the tests have passed, it will be showing green with a list of the successful tests and a code coverage report, letting you know what percentage of your application code was executed during the tests.

如果所有测试都通过了,它将以绿色显示,并带有成功测试的列表和代码覆盖率报告,让您知道在测试期间执行了应用程序代码的百分比。

模拟用户输入 ( Simulating User Input )

这是一个好的开始,但是确实很少有应用程序仅显示数据的情况。 我们要添加的下一个功能是使用户能够将新项目添加到他们的列表中。 为此,我们需要一个输入框,用户可以在其中输入新项目,还需要一个按钮,可以在单击时将项目添加到列表中。 这是List.vue的更新版本:
<template>
  <div>
    <h1>My To Do List</h1>
    </br>
    <input v-model="newItem" >
    <button @click="addItemToList">Add</button>
    <!-- displays list --> 
    <ul>
      <li v-for="item in listItems">{{ item }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'test',
  data () {
    return {
      listItems: ['buy food', 'play games', 'sleep'],
      newItem: ''
    }
  },
  methods: {
      addItemToList() {
        this.listItems.push(this.newItem);
        this.newItem = '';
      }
  }
}
</script>

Using v-model, the value of the input box is bound to newItem variable stored in the component's data. When the button is clicked, the function addItemToList gets executed which adds the newItem to the list array and clears the newItem so that more can be added to the list.

使用v-model ,输入框的值将绑定到存储在组件数据中的newItem变量。 单击按钮后,将执行addItemToList函数,该函数会将newItem添加到列表数组并清除newItem以便可以向列表添加更多内容。

To start testing this feature, create a new empty test in List.spec.js and add the test code as we go along:

要开始测试此功能,请在List.spec.js创建一个新的空测试,然后添加测试代码:

it('adds a new item to list on click', () => {
    // our test goes here
})

First we'll want to build our component and mimic a user typing in the input box. Since VueJS binds the value of the input box to the newItem variable, we can simply set our value to newItem.

首先,我们要构建我们的组件并模仿用户在输入框中键入内容。 由于VueJS将输入框的值绑定到newItem变量,因此我们可以简单地将我们的值设置为newItem

// build component
const Constructor = Vue.extend(List);
const ListComponent = new Constructor().$mount();

// set value of new item
ListComponent.newItem = 'brush my teeth';

Next we need to click the button. We have to find the button in the HTML, which is available with $el. Only this time we can use querySelector so as to find the actual element. It is possible to find an element using its class (.buttonClass), its id (#buttonId) or the element's name (button).

接下来,我们需要单击按钮。 我们必须在HTML中找到按钮,该按钮可用于$el 。 只有这次,我们才能使用querySelector来查找实际元素。 可以使用其类( .buttonClass ),其id( #buttonId )或元素的名称( button#buttonId元素。

// find button
const button = ListComponent.$el.querySelector('button');

To simulate a click, we need to pass the button a new event object to dispatch. In the testing environment, the List component won't be listening for any events and so we need to manually run the watcher.

为了模拟点击,我们需要向按钮传递一个新的事件对象以进行调度。 在测试环境中,List组件不会监听任何事件,因此我们需要手动运行观察程序。

// simulate click event
const clickEvent = new window.Event('click');
button.dispatchEvent(clickEvent);
ListComponent._watcher.run();

Finally we need to check that the newItem gets displayed, which we already know how to do from the first test! We might also want to check that the newItem gets stored in the list array.

最后,我们需要检查是否显示了newItem,从第一个测试中我们已经知道该怎么做! 我们可能还想检查newItem存储在列表数组中。

//assert list contains new item
expect(ListComponent.$el.textContent).to.contain('brush my teeth');
expect(ListComponent.listItems).to.contain('brush my teeth');

Here is the test file in full:

这是完整的测试文件:

import List from '@/components/List';
import Vue from 'vue';

describe('List.vue', () => {
  it('displays items from the list', () => {
    const Constructor = Vue.extend(List);
    const ListComponent = new Constructor().$mount();
    expect(ListComponent.$el.textContent).to.contain('play games');
  })

  it('adds a new item to list on click', () => {
    // build component
    const Constructor = Vue.extend(List);
    const ListComponent = new Constructor().$mount();

    // set input value
    ListComponent.newItem = 'brush my teeth';

    // simulate click event
    const button = ListComponent.$el.querySelector('button');
    const clickEvent = new window.Event('click');
    button.dispatchEvent(clickEvent);
    ListComponent._watcher.run();

    // assert list contains new item
    expect(ListComponent.$el.textContent).to.contain('brush my teeth');
    expect(ListComponent.listItems).to.contain('brush my teeth');
  })
})

Now we can run our tests again, and they should show green!

现在我们可以再次运行测试,它们应该显示为绿色!

Hopefully this code will be clear to you now, but it is not particularly readable, especially for someone making VueJS tests for the first time. There is a VueJS utility library which tucks away some of the more complicated looking code. To use it, we can go to our project root and run the following:

希望这段代码现在对您来说是清楚的,但是它并不是特别可读,特别是对于第一次进行VueJS测试的人。 有一个VueJS实用程序库,可以删除一些看起来更复杂的代码。 要使用它,我们可以转到项目根目录并运行以下命令:

npm install avoriaz

This test works exactly the same way as the one before except now we can hide the setup of the Vue component behind mount() and, for clicking the button, all we need is two lines of code: find() the button and dispatch() the click event.

该测试的工作方式与之前的测试完全相同,除了现在我们可以将Vue组件的设置隐藏在mount()后面,并且对于单击按钮,我们需要的是两行代码: find()按钮和dispatch()点击事件。

import { mount } from 'avoriaz';
import List from '@/components/List';
import Vue from 'vue';

describe('List.vue', () => {
  // previous tests ..

  it('adds new item to list on click with avoriaz', () => {
       // build component
    const ListComponent = mount(List);

    // set input value
    ListComponent.setData({
      newItem: 'brush my teeth',
    });

    // simulate click event
    const button = ListComponent.find('button')[0];
    button.dispatch('click');

    // assert list contains new item
    expect(ListComponent.text()).to.contain('brush my teeth');
    expect(ListComponent.data().listItems).to.contain('brush my teeth');
  })
})

结论 ( Conclusion )

我个人认为编写测试对我的正常工作流程至关重要,但是对于JavaScript尤其是VueJS,入门时遇到了一些麻烦。 希望本教程可以帮助与我处于同一职位的任何人!

Here is my Github repo with the code from this tutorial.

这是我的Github存储库 ,其中包含本教程中的代码。

翻译自: https://scotch.io/tutorials/how-to-write-a-unit-test-for-vuejs

编写vue.js用什么软件

更多推荐

编写vue.js用什么软件_如何为Vue.js编写单元测试