Skip to content

Commit a189eda

Browse files
authored
translated cookbook/unit-testing-vue-components.md (#691)
* translated cookbook/unit-testing-vue-components.md * Update unit-testing-vue-components.md * Update unit-testing-vue-components.md
1 parent 2928d9b commit a189eda

File tree

1 file changed

+73
-67
lines changed

1 file changed

+73
-67
lines changed

src/v2/cookbook/unit-testing-vue-components.md

+73-67
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
---
2-
title: Unit Testing Vue Components
2+
title: Vue 组件的单元测试
33
type: cookbook
44
order: 6
55
---
66

7-
## Simple Example
7+
## 简单的示例
88

9-
Unit testing is a fundamental part of software development. Unit tests execute the smallest units of code in isolation, in order to increase ease of adding new features and track down bugs. Vue's [single-file components](./single-file-components.html) make it straight forward to write unit tests for components in isolation. This lets you develop new features with confidence you are not breaking existing ones, and helps other developers understand what your component does.
9+
单元测试是软件开发非常基础的一部分。单元测试会封闭执行最小化单元的代码,使得添加新功能和追踪问题更容易。Vue[单文件组件](../guide/single-file-components.html)使得为组件撰写隔离的单元测试这件事更加直接。它会让你更有信心地开发新特性而不破坏现有的实现,并帮助其他开发者理解你的组件的作用。
1010

11-
This simple example tests whether some text is rendered:
11+
这是一个判断一些文本是否被渲染的简单的示例:
1212

1313
```html
1414
<template>
@@ -44,61 +44,63 @@ export default {
4444
```
4545

4646
```js
47-
import { shallow } from 'vue-test-utils'
47+
import { shallow } from '@vue/test-utils'
4848

4949
test('Foo', () => {
50-
// render the component
50+
// 渲染这个组件
5151
const wrapper = shallow(Hello)
5252

53-
// should not allow for username less than 7 characters, excludes whitespace
53+
// `username` 在除去头尾空格之后不应该少于 7 个字符
5454
wrapper.setData({ username: ' '.repeat(7) })
5555

56-
// assert the error is rendered
56+
 // 确认错误信息被渲染了
5757
expect(wrapper.find('.error').exists()).toBe(true)
5858

59-
// update the name to be long enough
59+
// 将名字更新至足够长
6060
wrapper.setData({
6161
username: {
6262
'Lachlan'
6363
}
6464
})
6565

66-
// assert the error has gone away
66+
// 断言错误信息不再显示了
6767
expect(wrapper.find('.error').exists()).toBe(false)
6868
})
6969
```
7070

71-
The above code snippet shows how to test whether an error message is rendered based on the length of the username. It demonstrates the general idea of unit testing Vue components: render the component, and assert that the markup matches the state of the component.
71+
上述代码片段展示了如何基于 `username` 的长度测试一个错误信息是否被渲染。它展示了 Vue 组件单元测试的一般思路:渲染这个组件,然后断言这些标签是否匹配组件的状态。
7272

73-
## Why test?
73+
## 为什么要测试?
7474

75-
Component unit tests have lots of benefits:
76-
- Provide documentation on how the component should behave
77-
- Save time over testing manually
78-
- Reduce bugs in new features
79-
- Improve design
80-
- Facilitate refactoring
75+
组件的单元测试有很多好处:
8176

82-
Automated testing allows large teams of developers to maintain complex codebases.
77+
- 提供描述组件行为的文档
78+
- 节省手动测试的时间
79+
- 减少研发新特性时产生的 bug
80+
- 改进设计
81+
- 促进重构
8382

84-
#### Getting started
83+
自动化测试使得大团队中的开发者可以维护复杂的基础代码。
8584

86-
[vue-test-utils](https://github.com/vuejs/vue-test-utils) is the official library for unit testing Vue components. The [vue-cli](https://github.com/vuejs/vue-cli) webpack template comes with either Karma or Jest, both well supported test runners, and there are some [guides](https://vue-test-utils.vuejs.org/en/guides/) in the `vue-test-utils` documentation.
85+
#### 起步
8786

88-
## Real-World Example
87+
[Vue Test Utils](https://github.com/vuejs/vue-test-utils) 是 Vue 组件单元测试的官方库。[Vue CLI](https://github.com/vuejs/vue-cli)`webpack` 模板对 Karma 和 Jest 这两个测试运行器都支持,并且在 Vue Test Utils 的文档中有一些[引导](https://vue-test-utils.vuejs.org/zh-cn/guides/)
8988

90-
Unit tests should be
91-
- Fast to run
92-
- Easy to understand
93-
- Only test a _single unit of work_
89+
## 实际的例子
9490

95-
Let's continue building on the previous example, while introducing the idea of a <a href="https://en.wikipedia.org/wiki/Factory_(object-oriented_programming)">factory function</a> to make our test more compact and readable. The component should:
91+
单元测试应该:
9692

97-
- show a 'Welcome to the Vue.js cookbook' greeting.
98-
- prompt the user to enter their username
99-
- display an error if the entered username is less than seven letters
93+
- 可以快速运行
94+
- 易于理解
95+
- 只测试_一个独立单元的工作_
10096

101-
Let's take a look at the component code first:
97+
我们在上一个示例的基础上继续构建,同时引入一个<a href="https://zh.wikipedia.org/wiki/工厂方法#工厂">工厂函数 (factory function)</a>使得我们的测试更简洁更易读。这个组件应该:
98+
99+
- 展示一个“Welcome to the Vue.js cookbook”的问候语
100+
- 提示用户输入用户名
101+
- 如果输入的用户名少于七个字符则展示错误信息
102+
103+
让我们先看一下组件代码:
102104

103105
```html
104106
<template>
@@ -136,15 +138,16 @@ export default {
136138
</script>
137139
```
138140

139-
The things that we should test are:
140-
- is the `message` rendered?
141-
- if `error` is `true`, `<div class="error"`> should be present
142-
- if `error` is `false`, `<div class="error"`> should not be present
141+
我们应该测试的内容有:
142+
143+
- `message` 是否被渲染
144+
- 如果 `error``true`,则 `<div class="error">` 应该展示
145+
- 如果 `error``false`,则 `<div class="error">` 不应该展示
143146

144-
And our first attempt at test:
147+
我们的第一次测试尝试:
145148

146149
```js
147-
import { shallow } from 'vue-test-utils'
150+
import { shallow } from '@vue/test-utils'
148151

149152
describe('Foo', () => {
150153
it('renders a message and responds correctly to user input', () => {
@@ -155,32 +158,35 @@ describe('Foo', () => {
155158
}
156159
})
157160

158-
// see if the message renders
161+
// 确认是否渲染了 `message`
159162
expect(wrapper.find('.message').text()).toEqual('Hello World')
160163

161-
// assert the error is rendered
164+
// 断言渲染了错误信息
162165
expect(wrapper.find('.error').exists()).toBeTruthy()
163166

164-
// update the username and assert error is longer rendered
165-
wrapper.setData({ username: 'Lachlan' })
167+
// 更新 `username` 并断言错误信息不再被渲染
168+
wrapper.setData({ username: 'Lachlan' })
166169
expect(wrapper.find('.error').exists()).toBeFalsy()
167170
})
168171
})
169172
```
170173

171-
There are some problems with the above:
172-
- a single test is making assertions about different things
173-
- difficult to tell the different states the component can be in, and what should be rendered
174+
上述代码有一些问题:
175+
176+
- 单个测试断言了不同的事情
177+
- 很难阐述组件可以处于哪些不同的状态,以及它该被渲染成什么样子
178+
179+
接下来的示例从这几个方面改善了测试:
180+
181+
- 每个 `it` 块只做一个断言
182+
- 让测试描述更简短清晰
183+
- 只提供测试需要的最小化数据
184+
- 把重复的逻辑重构到了一个工厂函数中 (创建 `wrapper` 和设置 `username` 变量)
174185

175-
The below example improves the test by:
176-
- only making one assertion per `it` block
177-
- having short, clear test descriptions
178-
- providing only the minimum data requires for the test
179-
- refactoring duplicated logic (creating the `wrapper` and setting the `username` variable) into a factory function
186+
*更新后的测试*
180187

181-
*Updated test*:
182188
```js
183-
import { shallow } from 'vue-test-utils'
189+
import { shallow } from '@vue/test-utils'
184190
import Foo from './Foo'
185191

186192
const factory = (values = {}) => {
@@ -216,32 +222,32 @@ describe('Foo', () => {
216222
})
217223
```
218224

219-
Points to note:
225+
注意事项:
220226

221-
At the top, we declare the factory function which merges the `values` object into `data` and returns a new `wrapper` instance. This way, we don't need to duplicate `const wrapper = shallow(Foo)` in every test. Another great benefit to this is when more complex components with a method or computed property you might want to mock or stub in every test, you only need to declare it once.
227+
在一开始,工厂函数将 `values` 对象合并到了 `data` 并返回了一个新的 `wrapper` 实例。这样,我们就不需要在每个测试中重复 `const wrapper = shallow(Foo)`。另一个好处是当你想为更复杂的组件在每个测试中伪造或存根一个方法或计算属性时,你只需要声明一次即可。
222228

223-
## Additional Context
229+
## 额外的上下文
224230

225-
The above test is fairly simple, but in practice Vue components often have other behaviors you want to test, such as:
231+
上述的测试是非常简单的,但是在实际情况下 Vue 组件常常具有其它你想要测试的行为,诸如:
226232

227-
- making API calls
228-
- committing or dispatching mutations or actions with a `Vuex` store
229-
- testing interaction
233+
- 调用 API
234+
- `Vuex` 的 store,commit 或 dispatch 一些 mutation 或 action
235+
- 测试用户交互
230236

231-
There are more complete examples showing such tests in the `vue-test-utils` [guides](https://vue-test-utils.vuejs.org/en/guides/).
237+
我们在 Vue Test Utils 的[教程](https://vue-test-utils.vuejs.org/zh-cn/guides/)中提供了更完整的示例展示这些测试。
232238

233-
`vue-test-utils` and the enormous JavaScript ecosystem provides plenty of tooling to facilitate almost 100% test coverage. Unit tests are only one part of the testing pyramid, though. Some other types of tests include e2e (end to end) tests, and snapshot tests. Unit tests are the smallest and most simple of tests - they make assertions on the smallest units of work, isolating each part of a single component.
239+
Vue Test Utils 及庞大的 JavaScript 生态系统提供了大量的工具促进 100% 的测试覆盖率。单元测试只是整个测试金字塔中的一部分。其它类型的测试还包括 e2e (端到端) 测试、快照比对测试等。单元测试是最小巧也是最简单的测试——它们通过隔离单个组件的每一个部分,来在最小工作单元上进行断言。
234240

235-
Snapshot tests save the markup of your Vue component, and compare to the new one generated each time the test runs. If something changes, the developer is notified, and can decide if the change was intentional (the component was updated) or accidentally (the component is behaving incorrectly).
241+
快照比对测试会保存你的 Vue 组件的标记,然后比较每次新生成的测试运行结果。如果有些东西改变了,开发者就会得到通知,并决定这个改变是刻意为之 (组件更新时) 还是意外发生的 (组件行为不正确)。
236242

237-
End to end tests involve ensure a number of components interact together well. They are more high level. Some examples might be testing if a user can sign up, log in, and update their username. These are slowly to run than unit tests or snapshot tests.
243+
端到端测试致力于确保组件的一系列交互是正确的。它们是更高级别的测试,例如可能会测试用户是否注册、登录以及更新他们的用户名。这种测试运行起来会比单元测试和快照比对测试慢一些。
238244

239-
Unit tests are most useful during development, either to help a developer think about how to design a component, or refactor an existing component, and are often run every time code is changed.
245+
单元测试中开发的时候是最有用的,即能帮助开发者思考如何设计一个组件或重构一个现有组件。通常每次代码发生变化的时候它们都会被运行。
240246

241-
Higher level tests, such as end to end tests, run much slower. These usually run pre-deploy, to ensure each part of the system is working together correctly.
247+
高级别的测试,诸如端到端测试,运行起来会更慢很多。这些测试通常只在部署前运行,来确保系统的每个部分都能够正常的协同工作。
242248

243-
More information about testing Vue components can be found in [Testing Vue.js Applications](https://www.manning.com/books/testing-vuejs-applications) by core team member [Edd Yerburgh](https://eddyerburgh.me/).
249+
更多测试 Vue 组件的知识可翻阅核心团员 [Edd Yerburgh](https://eddyerburgh.me/) 的书[《测试 Vue.js 应用》](https://www.manning.com/books/testing-vuejs-applications)
244250

245-
## When To Avoid This Pattern
251+
## 何时避免这个模式
246252

247-
Unit testing is an important part of any serious application. At first, when the vision of an application is not clear, unit testing might slow down development, but once a vision is established and real users will be interacting with the application, unit tests (and other types of automated tests) are absolutely essential to ensure the codebase is maintainable and scalable.
253+
单元测试是任何正经的应用的重要部分。一开始,当你对一个应用的愿景还不够清晰的时候,单元测试可能会拖慢开发进度,但是一旦你的愿景建立起来并且有真实的用户对这个应用产生兴趣,那么单元测试 (以及其它类型的自动化测试) 就是绝对有必要的了,它们会确保基础代码的可维护性和可扩展性。

0 commit comments

Comments
 (0)