2021-01-29 00:20:46 +05:30
---
stage: none
group: unassigned
2022-11-25 23:54:43 +05:30
info: To determine the technical writer assigned to the Stage/Group associated with this page, see https://about.gitlab.com/handbook/product/ux/technical-writing/#assignments
2021-01-29 00:20:46 +05:30
---
2017-08-17 22:00:37 +05:30
# Vue
2022-10-11 01:57:18 +05:30
To get started with Vue, read through [their documentation ](https://v2.vuejs.org/v2/guide/index.html ).
2017-08-17 22:00:37 +05:30
2018-11-18 11:00:15 +05:30
## Examples
2017-08-17 22:00:37 +05:30
2018-11-18 11:00:15 +05:30
What is described in the following sections can be found in these examples:
2018-03-17 18:26:18 +05:30
2020-06-23 00:09:42 +05:30
- [Web IDE ](https://gitlab.com/gitlab-org/gitlab-foss/tree/master/app/assets/javascripts/ide/stores )
2021-09-04 01:27:46 +05:30
- [Security products ](https://gitlab.com/gitlab-org/gitlab/-/tree/master/ee/app/assets/javascripts/vue_shared/security_reports )
2020-06-23 00:09:42 +05:30
- [Registry ](https://gitlab.com/gitlab-org/gitlab-foss/tree/master/app/assets/javascripts/registry/stores )
2017-08-17 22:00:37 +05:30
2018-11-18 11:00:15 +05:30
## Vue architecture
2017-08-17 22:00:37 +05:30
2020-05-24 23:13:21 +05:30
All new features built with Vue.js must follow a [Flux architecture ](https://facebook.github.io/flux/ ).
2022-08-13 15:12:31 +05:30
The main goal we are trying to achieve is to have only one data flow, and only one data entry.
To achieve this goal we use [Vuex ](#vuex ).
2017-08-17 22:00:37 +05:30
2021-03-11 19:13:27 +05:30
You can also read about this architecture in Vue documentation about
2022-10-11 01:57:18 +05:30
[state management ](https://v2.vuejs.org/v2/guide/state-management.html#Simple-State-Management-from-Scratch )
and about [one way data flow ](https://v2.vuejs.org/v2/guide/components-props.html#One-Way-Data-Flow ).
2017-08-17 22:00:37 +05:30
2018-11-18 11:00:15 +05:30
### Components and Store
2017-08-17 22:00:37 +05:30
2020-05-24 23:13:21 +05:30
In some features implemented with Vue.js, like the [issue board ](https://gitlab.com/gitlab-org/gitlab-foss/tree/master/app/assets/javascripts/boards )
or [environments table ](https://gitlab.com/gitlab-org/gitlab-foss/tree/master/app/assets/javascripts/environments )
2017-08-17 22:00:37 +05:30
you can find a clear separation of concerns:
2020-04-22 19:07:51 +05:30
```plaintext
2017-08-17 22:00:37 +05:30
new_feature
├── components
2018-05-09 12:01:36 +05:30
│ └── component.vue
2017-08-17 22:00:37 +05:30
│ └── ...
2018-11-18 11:00:15 +05:30
├── store
2018-05-09 12:01:36 +05:30
│ └── new_feature_store.js
2018-10-15 14:42:47 +05:30
├── index.js
2017-08-17 22:00:37 +05:30
```
2019-09-30 21:07:59 +05:30
2017-08-17 22:00:37 +05:30
_For consistency purposes, we recommend you to follow the same structure._
Let's look into each of them:
2019-07-31 22:56:46 +05:30
### An `index.js` file
2017-08-17 22:00:37 +05:30
2022-08-13 15:12:31 +05:30
This file is the index file of your new feature. The root Vue instance
of the new feature should be here.
2017-08-17 22:00:37 +05:30
The Store and the Service should be imported and initialized in this file and
provided as a prop to the main component.
2021-01-29 00:20:46 +05:30
Be sure to read about [page-specific JavaScript ](performance.md#page-specific-javascript ).
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
### Bootstrapping Gotchas
2019-09-30 21:07:59 +05:30
2018-11-08 19:23:39 +05:30
#### Providing data from HAML to JavaScript
2019-09-30 21:07:59 +05:30
2020-07-28 23:09:34 +05:30
While mounting a Vue application, you might need to provide data from Rails to JavaScript.
To do that, you can use the `data` attributes in the HTML element and query them while mounting the application.
2021-03-08 18:12:59 +05:30
You should only do this while initializing the application, because the mounted element is replaced
with a Vue-generated DOM.
2018-03-17 18:26:18 +05:30
2023-01-13 00:05:48 +05:30
The `data` attributes are [only able to accept String values ](https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes#javascript_access ),
so you will need to cast or convert other variable types to String.
2021-10-27 15:23:28 +05:30
The advantage of providing data from the DOM to the Vue instance through `props` or
`provide` in the `render` function, instead of querying the DOM inside the main Vue
2022-08-13 15:12:31 +05:30
component, is that you avoid creating a fixture or an HTML element in the unit test.
2021-01-29 00:20:46 +05:30
2023-04-23 21:23:45 +05:30
##### The `initSimpleApp` helper
`initSimpleApp` is a helper function that streamlines the process of mounting a component in Vue.js. It accepts two arguments: a selector string representing the mount point in the HTML, and a Vue component.
2023-05-27 22:25:52 +05:30
To use `initSimpleApp` :
1. Include an HTML element in the page with an ID or unique class.
1. Add a data-view-model attribute containing a JSON object.
1. Import the desired Vue component, and pass it along with a valid CSS selector string
that selects the HTML element to `initSimpleApp` . This string mounts the component
at the specified location.
2023-04-23 21:23:45 +05:30
`initSimpleApp` automatically retrieves the content of the data-view-model attribute as a JSON object and passes it as props to the mounted Vue component. This can be used to pre-populate the component with data.
Example:
```vue
//my_component.vue
< template >
< div >
< p > Prop1: {{ prop1 }}< / p >
< p > Prop2: {{ prop2 }}< / p >
< / div >
< / template >
< script >
export default {
name: 'MyComponent',
props: {
prop1: {
type: String,
required: true
},
prop2: {
type: Number,
required: true
}
}
}
< / script >
```
```html
< div id = "js-my-element" data-view-model = '{"prop1": "my object", "prop2": 42 }' > < / div >
```
```javascript
//index.js
import MyComponent from './my_component.vue'
import initSimpleApp from '~/helpers/init_simple_app_helper'
initSimpleApp('#js-my-element', MyComponent)
```
2022-08-13 15:12:31 +05:30
##### `provide` and `inject`
2021-10-27 15:23:28 +05:30
2022-08-27 11:52:29 +05:30
Vue supports dependency injection through [`provide` and `inject` ](https://v2.vuejs.org/v2/api/#provide-inject ).
2022-01-26 12:08:38 +05:30
In the component the `inject` configuration accesses the values `provide` passes down.
2021-12-11 22:18:48 +05:30
This example of a Vue app initialization shows how the `provide` configuration passes a value from HAML to the component:
2021-10-27 15:23:28 +05:30
```javascript
#js-vue-app{ data: { endpoint: 'foo' }}
// index.js
const el = document.getElementById('js-vue-app');
if (!el) return false;
const { endpoint } = el.dataset;
return new Vue({
el,
2023-05-27 22:25:52 +05:30
name: 'MyComponentRoot',
2021-10-27 15:23:28 +05:30
render(createElement) {
return createElement('my-component', {
provide: {
endpoint
},
});
},
});
```
The component, or any of its child components, can access the property through `inject` as:
```vue
< script >
export default {
name: 'MyComponent',
inject: ['endpoint'],
...
...
};
< / script >
< template >
...
...
< / template >
```
Using dependency injection to provide values from HAML is ideal when:
- The injected value doesn't need an explicit validation against its data type or contents.
- The value doesn't need to be reactive.
2022-08-13 15:12:31 +05:30
- Multiple components exist in the hierarchy that need access to this value where
2021-10-27 15:23:28 +05:30
prop-drilling becomes an inconvenience. Prop-drilling when the same prop is passed
through all components in the hierarchy until the component that is genuinely using it.
2022-08-13 15:12:31 +05:30
Dependency injection can potentially break a child component (either an immediate child or multiple levels deep) if both conditions are true:
- The value declared in the `inject` configuration doesn't have defaults defined.
- The parent component has not provided the value using the `provide` configuration.
2022-06-21 17:19:12 +05:30
2022-08-13 15:12:31 +05:30
A [default value ](https://vuejs.org/guide/components/provide-inject.html#injection-default-values ) might be useful in contexts where it makes sense.
2022-06-21 17:19:12 +05:30
2021-10-27 15:23:28 +05:30
##### props
If the value from HAML doesn't fit the criteria of dependency injection, use `props` .
See the following example.
2018-03-17 18:26:18 +05:30
```javascript
// haml
2020-10-24 23:57:45 +05:30
#js-vue-app{ data: { endpoint: 'foo' }}
2018-03-17 18:26:18 +05:30
2018-11-08 19:23:39 +05:30
// index.js
2021-01-29 00:20:46 +05:30
const el = document.getElementById('js-vue-app');
if (!el) return false;
const { endpoint } = el.dataset;
return new Vue({
el,
2023-05-27 22:25:52 +05:30
name: 'MyComponentRoot',
2018-03-17 18:26:18 +05:30
render(createElement) {
return createElement('my-component', {
props: {
2021-01-29 00:20:46 +05:30
endpoint
2018-03-17 18:26:18 +05:30
},
});
},
2021-02-22 17:27:13 +05:30
});
2018-03-17 18:26:18 +05:30
```
2022-08-13 15:12:31 +05:30
NOTE:
When adding an `id` attribute to mount a Vue application, make sure this `id` is unique
2021-03-08 18:12:59 +05:30
across the codebase.
2020-10-24 23:57:45 +05:30
2021-10-27 15:23:28 +05:30
For more information on why we explicitly declare the data being passed into the Vue app,
refer to our [Vue style guide ](style/vue.md#basic-rules ).
2021-04-29 21:17:54 +05:30
#### Providing Rails form fields to Vue applications
When composing a form with Rails, the `name` , `id` , and `value` attributes of form inputs are generated
2021-06-08 01:23:25 +05:30
to match the backend. It can be helpful to have access to these generated attributes when converting
2022-08-13 15:12:31 +05:30
a Rails form to Vue, or when [integrating components ](https://gitlab.com/gitlab-org/gitlab/-/blob/8956ad767d522f37a96e03840595c767de030968/app/assets/javascripts/access_tokens/index.js#L15 ) (such as a date picker or project selector) into it.
2021-06-08 01:23:25 +05:30
The [`parseRailsFormFields` ](https://gitlab.com/gitlab-org/gitlab/-/blob/fe88797f682c7ff0b13f2c2223a3ff45ada751c1/app/assets/javascripts/lib/utils/forms.js#L107 ) utility can be used to parse the generated form input attributes so they can be passed to the Vue application.
2022-08-13 15:12:31 +05:30
This enables us to integrate Vue components without changing how the form submits.
2021-04-29 21:17:54 +05:30
```haml
-# form.html.haml
= form_for user do |form|
.js-user-form
= form.text_field :name, class: 'form-control gl-form-input', data: { js_name: 'name' }
= form.text_field :email, class: 'form-control gl-form-input', data: { js_name: 'email' }
```
> The `js_name` data attribute is used as the key in the resulting JavaScript object.
2021-06-08 01:23:25 +05:30
For example `= form.text_field :email, data: { js_name: 'fooBarBaz' }` would be translated
2021-04-29 21:17:54 +05:30
to `{ fooBarBaz: { name: 'user[email]', id: 'user_email', value: '' } }`
```javascript
// index.js
import Vue from 'vue';
import { parseRailsFormFields } from '~/lib/utils/forms';
import UserForm from './components/user_form.vue';
export const initUserForm = () => {
const el = document.querySelector('.js-user-form');
if (!el) {
return null;
}
const fields = parseRailsFormFields(el);
return new Vue({
el,
2023-05-27 22:25:52 +05:30
name: 'UserFormRoot',
2021-04-29 21:17:54 +05:30
render(h) {
return h(UserForm, {
props: {
fields,
},
});
},
});
};
```
```vue
< script >
// user_form.vue
import { GlButton, GlFormGroup, GlFormInput } from '@gitlab/ui';
export default {
name: 'UserForm',
components: { GlButton, GlFormGroup, GlFormInput },
props: {
fields: {
type: Object,
required: true,
},
},
};
< / script >
< template >
< div >
< gl-form-group :label-for = "fields.name.id" :label = "__('Name')" >
< gl-form-input v-bind = "fields.name" size = "lg" / >
< / gl-form-group >
< gl-form-group :label-for = "fields.email.id" :label = "__('Email')" >
< gl-form-input v-bind = "fields.email" type = "email" size = "lg" / >
< / gl-form-group >
< gl-button type = "submit" category = "primary" variant = "confirm" > {{ __ ('Update') }}</ gl-button >
< / div >
< / template >
```
2018-03-17 18:26:18 +05:30
#### Accessing the `gl` object
2019-09-30 21:07:59 +05:30
2021-03-11 19:13:27 +05:30
We query the `gl` object for data that doesn't change during the application's life
cycle in the same place we query the DOM. By following this practice, we can
2022-08-13 15:12:31 +05:30
avoid mocking the `gl` object, which makes tests easier. It should be done while
2021-03-08 18:12:59 +05:30
initializing our Vue instance, and the data should be provided as `props` to the main component:
2018-03-17 18:26:18 +05:30
```javascript
2021-01-29 00:20:46 +05:30
return new Vue({
2018-03-17 18:26:18 +05:30
el: '.js-vue-app',
2023-05-27 22:25:52 +05:30
name: 'MyComponentRoot',
2018-03-17 18:26:18 +05:30
render(createElement) {
return createElement('my-component', {
props: {
2021-12-11 22:18:48 +05:30
avatarUrl: gl.avatarUrl,
2018-03-17 18:26:18 +05:30
},
});
},
2021-01-29 00:20:46 +05:30
});
2018-03-17 18:26:18 +05:30
```
2019-12-21 20:55:43 +05:30
#### Accessing feature flags
2022-08-27 11:52:29 +05:30
Use the [`provide` and `inject` ](https://v2.vuejs.org/v2/api/#provide-inject ) mechanisms
2022-08-13 15:12:31 +05:30
in Vue to make feature flags available to any descendant components in a Vue
2019-12-21 20:55:43 +05:30
application. The `glFeatures` object is already provided in `commons/vue.js` , so
2021-01-29 00:20:46 +05:30
only the mixin is required to use the flags:
2019-12-21 20:55:43 +05:30
```javascript
// An arbitrary descendant component
import glFeatureFlagsMixin from '~/vue_shared/mixins/gl_feature_flags_mixin';
export default {
// ...
mixins: [glFeatureFlagsMixin()],
// ...
created() {
if (this.glFeatures.myFlag) {
// ...
}
},
}
```
This approach has a few benefits:
- Arbitrarily deeply nested components can opt-in and access the flag without
intermediate components being aware of it (c.f. passing the flag down via
props).
2021-03-11 19:13:27 +05:30
- Good testability, because the flag can be provided to `mount` /`shallowMount`
from `vue-test-utils` as a prop.
2019-12-21 20:55:43 +05:30
```javascript
import { shallowMount } from '@vue/test-utils';
shallowMount(component, {
provide: {
glFeatures: { myFlag: true },
},
});
```
2022-08-13 15:12:31 +05:30
- Accessing a global variable is not required, except in the application's
2019-12-21 20:55:43 +05:30
[entry point ](#accessing-the-gl-object ).
2017-08-17 22:00:37 +05:30
### A folder for Components
2021-02-22 17:27:13 +05:30
This folder holds all components that are specific to this new feature.
2022-08-13 15:12:31 +05:30
To use or create a component that is likely to be used somewhere
else, refer to `vue_shared/components` .
2017-08-17 22:00:37 +05:30
2022-01-26 12:08:38 +05:30
A good guideline to know when you should create a component is to think if
2021-02-22 17:27:13 +05:30
it could be reusable elsewhere.
2017-08-17 22:00:37 +05:30
For example, tables are used in a quite amount of places across GitLab, a table
would be a good fit for a component. On the other hand, a table cell used only
in one table would not be a good use of this pattern.
2022-10-11 01:57:18 +05:30
You can read more about components in Vue.js site, [Component System ](https://v2.vuejs.org/v2/guide/#Composing-with-Components ).
2017-08-17 22:00:37 +05:30
### A folder for the Store
2018-10-15 14:42:47 +05:30
#### Vuex
2019-09-30 21:07:59 +05:30
2018-10-15 14:42:47 +05:30
Check this [page ](vuex.md ) for more details.
2019-07-07 11:18:12 +05:30
### Mixing Vue and jQuery
- Mixing Vue and jQuery is not recommended.
2022-08-13 15:12:31 +05:30
- To use a specific jQuery plugin in Vue, [create a wrapper around it ](https://vuejs.org/v2/examples/select2.html ).
2019-07-07 11:18:12 +05:30
- It is acceptable for Vue to listen to existing jQuery events using jQuery event listeners.
- It is not recommended to add new jQuery events for Vue to interact with jQuery.
2021-01-29 00:20:46 +05:30
### Mixing Vue and JavaScript classes (in the data function)
2022-08-27 11:52:29 +05:30
In the [Vue documentation ](https://v2.vuejs.org/v2/api/#Options-Data ) the Data function/object is defined as follows:
2021-01-29 00:20:46 +05:30
2021-03-08 18:12:59 +05:30
> The data object for the Vue instance. Vue recursively converts its properties into getter/setters
2021-04-29 21:17:54 +05:30
to make it "reactive". The object must be plain: native objects such as browser API objects and
2022-01-26 12:08:38 +05:30
prototype properties are ignored. A guideline is that data should just be data - it is not
2021-03-08 18:12:59 +05:30
recommended to observe objects with their own stateful behavior.
2021-01-29 00:20:46 +05:30
Based on the Vue guidance:
2022-10-11 01:57:18 +05:30
- **Do not** use or create a JavaScript class in your [data function ](https://v2.vuejs.org/v2/api/#data ).
2021-01-29 00:20:46 +05:30
- **Do not** add new JavaScript class implementations.
2021-03-08 18:12:59 +05:30
- **Do** use [GraphQL ](../api_graphql_styleguide.md ), [Vuex ](vuex.md ) or a set of components if
2021-03-11 19:13:27 +05:30
cannot use primitives or objects.
2021-01-29 00:20:46 +05:30
- **Do** maintain existing implementations using such approaches.
- **Do** Migrate components to a pure object model when there are substantial changes to it.
2021-03-11 19:13:27 +05:30
- **Do** add business logic to helpers or utilities, so you can test them separately from your component.
2021-01-29 00:20:46 +05:30
#### Why
2022-08-13 15:12:31 +05:30
Additional reasons why having a JavaScript class presents maintainability issues on a huge codebase:
2021-01-29 00:20:46 +05:30
2021-03-11 19:13:27 +05:30
- After a class is created, it can be extended in a way that can infringe Vue reactivity and best practices.
2021-01-29 00:20:46 +05:30
- A class adds a layer of abstraction, which makes the component API and its inner workings less clear.
2021-03-11 19:13:27 +05:30
- It makes it harder to test. Because the class is instantiated by the component data function, it is
2021-03-08 18:12:59 +05:30
harder to 'manage' component and class separately.
2022-08-13 15:12:31 +05:30
- Adding Object Oriented Principles (OOP) to a functional codebase adds another way of writing code, reducing consistency and clarity.
2021-01-29 00:20:46 +05:30
2017-08-17 22:00:37 +05:30
## Style guide
2022-08-13 15:12:31 +05:30
Refer to the Vue section of our [style guide ](style/vue.md )
2021-01-29 00:20:46 +05:30
for best practices while writing and testing your Vue components and templates.
2017-08-17 22:00:37 +05:30
2022-08-13 15:12:31 +05:30
## Composition API
With Vue 2.7 it is possible to use [Composition API ](https://vuejs.org/guide/introduction.html#api-styles ) in Vue components and as standalone composables.
### Prefer `<script>` over `<script setup>`
Composition API allows you to place the logic in the `<script>` section of the component or to have a dedicated `<script setup>` section. We should use `<script>` and add Composition API to components using `setup()` property:
```html
< script >
import { computed } from 'vue';
export default {
name: 'MyComponent',
setup(props) {
const doubleCount = computed(() => props.count*2)
}
}
< / script >
```
2023-05-27 22:25:52 +05:30
### `v-bind` limitations
Avoid using `v-bind="$attrs"` unless absolutely necessary. You might need this when
developing a native control wrapper. (This is a good candidate for a `gitlab-ui` component.)
In any other cases, always prefer using `props` and explicit data flow.
Using `v-bind="$attrs"` leads to:
1. A loss in component's contract. The `props` were designed specifically
to address this problem.
1. High maintenance cost for each component in the tree. `v-bind="$attrs"` is specifically
hard to debug because you must scan the whole hierarchy of components to understand
the data flow.
1. Problems during migration to Vue 3. `$attrs` in Vue 3 include event listeners which
could cause unexpected side-effects after Vue 3 migration is completed.
2022-08-13 15:12:31 +05:30
### Aim to have one API style per component
When adding `setup()` property to Vue component, consider refactoring it to Composition API entirely. It's not always feasible, especially for large components, but we should aim to have one API style per component for readability and maintainability.
### Composables
With Composition API, we have a new way of abstracting logic including reactive state to _composables_ . Composable is the function that can accept parameters and return reactive properties and methods to be used in Vue component.
```javascript
// useCount.js
import { ref } from 'vue';
export function useCount(initialValue) {
const count = ref(initialValue)
function incrementCount() {
2022-11-25 23:54:43 +05:30
count.value += 1
2022-08-13 15:12:31 +05:30
}
function decrementCount() {
2022-11-25 23:54:43 +05:30
count.value -= 1
2022-08-13 15:12:31 +05:30
}
return { count, incrementCount, decrementCount }
}
```
```javascript
// MyComponent.vue
import { useCount } from 'useCount'
export default {
name: 'MyComponent',
setup() {
const { count, incrementCount, decrementCount } = useCount(5)
return { count, incrementCount, decrementCount }
}
}
```
#### Prefix function and file names with `use`
Common naming convention in Vue for composables is to prefix them with `use` and then refer to composable functionality briefly (`useBreakpoints`, `useGeolocation` etc). The same rule applies to the `.js` files containing composables - they should start with `use_` even if the file contains more than one composable.
#### Avoid lifecycle pitfalls
When building a composable, we should aim to keep it as simple as possible. Lifecycle hooks add complexity to composables and might lead to unexpected side effects. To avoid that we should follow these principles:
- Minimize lifecycle hooks usage whenever possible, prefer accepting/returning callbacks instead.
- If your composable needs lifecycle hooks, make sure it also performs a cleanup. If we add a listener on `onMounted` , we should remove it on `onUnmounted` within the same composable.
- Always set up lifecycle hooks immediately:
```javascript
// bad
const useAsyncLogic = () => {
const action = async () => {
await doSomething();
onMounted(doSomethingElse);
};
return { action };
};
// OK
const useAsyncLogic = () => {
const done = ref(false);
onMounted(() => {
watch(
done,
() => done.value & & doSomethingElse(),
{ immediate: true },
);
});
const action = async () => {
await doSomething();
done.value = true;
};
return { action };
};
```
#### Avoid escape hatches
It might be tempting to write a composable that does everything as a black box, using some of the escape hatches that Vue provides. But for most of the cases this makes them too complex and hard to maintain. One escape hatch is the `getCurrentInstance` method. This method returns an instance of a current rendering component. Instead of using that method, you should prefer passing down the data or methods to a composable via arguments.
```javascript
const useSomeLogic = () => {
doSomeLogic();
getCurrentInstance().emit('done'); // bad
};
```
```javascript
const done = () => emit('done');
const useSomeLogic = (done) => {
doSomeLogic();
done(); // good, composable doesn't try to be too smart
}
```
#### Composables and Vuex
We should always prefer to avoid using Vuex state in composables. In case it's not possible, we should use props to receive that state, and emit events from the `setup` to update the Vuex state. A parent component should be responsible to get that state from Vuex, and mutate it on events emitted from a child. You should **never mutate a state that's coming down from a prop** . If a composable must mutate a Vuex state, it should use a callback to emit an event.
```javascript
const useAsyncComposable = ({ state, update }) => {
const start = async () => {
const newState = await doSomething(state);
update(newState);
};
return { start };
};
const ComponentWithComposable = {
setup(props, { emit }) {
const update = (data) => emit('update', data);
const state = computed(() => props.state); // state from Vuex
const { start } = useAsyncComposable({ state, update });
start();
},
};
```
#### Testing composables
<!-- TBD -->
2017-08-17 22:00:37 +05:30
## Testing Vue Components
2022-08-13 15:12:31 +05:30
Refer to the [Vue testing style guide ](style/vue.md#vue-testing )
2021-01-29 00:20:46 +05:30
for guidelines and best practices for testing your Vue components.
2017-08-17 22:00:37 +05:30
Each Vue component has a unique output. This output is always present in the render function.
2021-03-11 19:13:27 +05:30
Although each method of a Vue component can be tested individually, our goal is to test the output
of the render function, which represents the state at all times.
2017-08-17 22:00:37 +05:30
2022-10-11 01:57:18 +05:30
Visit the [Vue testing guide ](https://v2.vuejs.org/v2/guide/testing.html#Unit-Testing ) for help.
2021-04-17 20:07:23 +05:30
2020-05-24 23:13:21 +05:30
Here's an example of a well structured unit test for [this Vue component ](#appendix---vue-component-subject-under-test ):
2017-08-17 22:00:37 +05:30
```javascript
2020-05-24 23:13:21 +05:30
import { GlLoadingIcon } from '@gitlab/ui';
2018-11-08 19:23:39 +05:30
import MockAdapter from 'axios-mock-adapter';
2021-09-04 01:27:46 +05:30
import { shallowMountExtended } from 'helpers/vue_test_utils_helper';
2020-05-24 23:13:21 +05:30
import axios from '~/lib/utils/axios_utils';
import App from '~/todos/app.vue';
2021-09-04 01:27:46 +05:30
const TEST_TODOS = [{ text: 'Lorem ipsum test text' }, { text: 'Lorem ipsum 2' }];
2020-05-24 23:13:21 +05:30
const TEST_NEW_TODO = 'New todo title';
const TEST_TODO_PATH = '/todos';
2017-08-17 22:00:37 +05:30
2020-05-24 23:13:21 +05:30
describe('~/todos/app.vue', () => {
let wrapper;
2018-11-08 19:23:39 +05:30
let mock;
beforeEach(() => {
2020-05-24 23:13:21 +05:30
// IMPORTANT: Use axios-mock-adapter for stubbing axios API requests
2018-11-08 19:23:39 +05:30
mock = new MockAdapter(axios);
2020-05-24 23:13:21 +05:30
mock.onGet(TEST_TODO_PATH).reply(200, TEST_TODOS);
mock.onPost(TEST_TODO_PATH).reply(200);
2018-11-08 19:23:39 +05:30
});
afterEach(() => {
2023-05-27 22:25:52 +05:30
// IMPORTANT: Clean up the axios mock adapter
2020-05-24 23:13:21 +05:30
mock.restore();
2017-08-17 22:00:37 +05:30
});
2021-01-29 00:20:46 +05:30
// It is very helpful to separate setting up the component from
2021-03-08 18:12:59 +05:30
// its collaborators (for example, Vuex and axios).
2020-05-24 23:13:21 +05:30
const createWrapper = (props = {}) => {
2021-09-04 01:27:46 +05:30
wrapper = shallowMountExtended(App, {
propsData: {
path: TEST_TODO_PATH,
...props,
},
});
2020-05-24 23:13:21 +05:30
};
2021-01-29 00:20:46 +05:30
// Helper methods greatly help test maintainability and readability.
2021-09-04 01:27:46 +05:30
const findLoader = () => wrapper.findComponent(GlLoadingIcon);
2021-03-08 18:12:59 +05:30
const findAddButton = () => wrapper.findByTestId('add-button');
const findTextInput = () => wrapper.findByTestId('text-input');
2021-09-04 01:27:46 +05:30
const findTodoData = () =>
wrapper
.findAllByTestId('todo-item')
.wrappers.map((item) => ({ text: item.text() }));
2020-05-24 23:13:21 +05:30
describe('when mounted and loading', () => {
beforeEach(() => {
// Create request which will never resolve
mock.onGet(TEST_TODO_PATH).reply(() => new Promise(() => {}));
createWrapper();
});
2017-08-17 22:00:37 +05:30
2020-05-24 23:13:21 +05:30
it('should render the loading state', () => {
expect(findLoader().exists()).toBe(true);
2017-08-17 22:00:37 +05:30
});
2018-11-08 19:23:39 +05:30
});
2017-08-17 22:00:37 +05:30
2020-05-24 23:13:21 +05:30
describe('when todos are loaded', () => {
beforeEach(() => {
createWrapper();
// IMPORTANT: This component fetches data asynchronously on mount, so let's wait for the Vue template to update
return wrapper.vm.$nextTick();
});
2017-08-17 22:00:37 +05:30
2020-05-24 23:13:21 +05:30
it('should not show loading', () => {
expect(findLoader().exists()).toBe(false);
});
2017-08-17 22:00:37 +05:30
2020-05-24 23:13:21 +05:30
it('should render todos', () => {
expect(findTodoData()).toEqual(TEST_TODOS);
2017-08-17 22:00:37 +05:30
});
2021-09-04 01:27:46 +05:30
it('when todo is added, should post new todo', async () => {
findTextInput().vm.$emit('update', TEST_NEW_TODO);
2020-05-24 23:13:21 +05:30
findAddButton().vm.$emit('click');
2017-08-17 22:00:37 +05:30
2021-09-04 01:27:46 +05:30
await wrapper.vm.$nextTick();
expect(mock.history.post.map((x) => JSON.parse(x.data))).toEqual([{ text: TEST_NEW_TODO }]);
2017-08-17 22:00:37 +05:30
});
});
});
```
2018-11-08 19:23:39 +05:30
2021-03-08 18:12:59 +05:30
### Child components
1. Test any directive that defines if/how child component is rendered (for example, `v-if` and `v-for` ).
1. Test any props we are passing to child components (especially if the prop is calculated in the
component under test, with the `computed` property, for example). Remember to use `.props()` and not `.vm.someProp` .
1. Test we react correctly to any events emitted from child components:
```javascript
const checkbox = wrapper.findByTestId('checkboxTestId');
2021-03-11 19:13:27 +05:30
2021-03-08 18:12:59 +05:30
expect(checkbox.attributes('disabled')).not.toBeDefined();
2021-03-11 19:13:27 +05:30
2021-03-08 18:12:59 +05:30
findChildComponent().vm.$emit('primary');
await nextTick();
2021-03-11 19:13:27 +05:30
2021-03-08 18:12:59 +05:30
expect(checkbox.attributes('disabled')).toBeDefined();
```
1. **Do not** test the internal implementation of the child components:
```javascript
// bad
expect(findChildComponent().find('.error-alert').exists()).toBe(false);
2021-03-11 19:13:27 +05:30
2021-03-08 18:12:59 +05:30
// good
expect(findChildComponent().props('withAlertContainer')).toBe(false);
```
2020-05-24 23:13:21 +05:30
### Events
2022-08-13 15:12:31 +05:30
We should test for events emitted in response to an action in our component. This testing
verifies the correct events are being fired with the correct arguments.
2020-05-24 23:13:21 +05:30
2022-06-21 17:19:12 +05:30
For any DOM events we should use [`trigger` ](https://v1.test-utils.vuejs.org/api/wrapper/#trigger )
2021-03-08 18:12:59 +05:30
to fire out event.
2018-03-17 18:26:18 +05:30
```javascript
2020-05-24 23:13:21 +05:30
// Assuming SomeButton renders: < button > Some button< / button >
wrapper = mount(SomeButton);
2018-03-17 18:26:18 +05:30
2020-05-24 23:13:21 +05:30
...
it('should fire the click event', () => {
const btn = wrapper.find('button')
btn.trigger('click');
...
})
2018-03-17 18:26:18 +05:30
```
2022-10-11 01:57:18 +05:30
When firing a Vue event, use [`emit` ](https://v2.vuejs.org/v2/guide/components-custom-events.html ).
2019-09-30 21:07:59 +05:30
2020-05-24 23:13:21 +05:30
```javascript
wrapper = shallowMount(DropdownItem);
...
it('should fire the itemClicked event', () => {
DropdownItem.vm.$emit('itemClicked');
...
})
```
2021-03-08 18:12:59 +05:30
We should verify an event has been fired by asserting against the result of the
2022-06-21 17:19:12 +05:30
[`emitted()` ](https://v1.test-utils.vuejs.org/api/wrapper/#emitted ) method.
2017-08-17 22:00:37 +05:30
2019-02-15 15:39:39 +05:30
## Vue.js Expert Role
2019-09-30 21:07:59 +05:30
2020-07-28 23:09:34 +05:30
You should only apply to be a Vue.js expert when your own merge requests and your reviews show:
2019-07-07 11:18:12 +05:30
2020-01-01 13:55:28 +05:30
- Deep understanding of Vue and Vuex reactivity
2019-02-15 15:39:39 +05:30
- Vue and Vuex code are structured according to both official and our guidelines
- Full understanding of testing a Vue and Vuex application
2020-05-24 23:13:21 +05:30
- Vuex code follows the [documented pattern ](vuex.md#naming-pattern-request-and-receive-namespaces )
2019-02-15 15:39:39 +05:30
- Knowledge about the existing Vue and Vuex applications and existing reusable components
2020-05-24 23:13:21 +05:30
## Vue 2 -> Vue 3 Migration
> This section is added temporarily to support the efforts to migrate the codebase from Vue 2.x to Vue 3.x
2021-03-11 19:13:27 +05:30
We recommend to minimize adding certain features to the codebase to prevent increasing
2021-03-08 18:12:59 +05:30
the tech debt for the eventual migration:
2020-05-24 23:13:21 +05:30
- filters;
- event buses;
- functional templated
- `slot` attributes
You can find more details on [Migration to Vue 3 ](vue3_migration.md )
## Appendix - Vue component subject under test
2021-03-08 18:12:59 +05:30
This is the template for the example component which is tested in the
[Testing Vue components ](#testing-vue-components ) section:
2020-05-24 23:13:21 +05:30
```html
< template >
< div class = "content" >
< gl-loading-icon v-if = "isLoading" / >
< template v-else >
< div
v-for="todo in todos"
:key="todo.id"
:class="{ 'gl-strike': todo.isDone }"
data-testid="todo-item"
>{{ toddo.text }}< / div >
< footer class = "gl-border-t-1 gl-mt-3 gl-pt-3" >
< gl-form-input
type="text"
v-model="todoText"
data-testid="text-input"
>
< gl-button
2022-07-23 23:45:48 +05:30
variant="confirm"
2020-05-24 23:13:21 +05:30
data-testid="add-button"
@click ="addTodo"
>Add< / gl-button >
< / footer >
< / template >
< / div >
< / template >
```