Skip to content

Guide: testing-SFCs-with-jest.md #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Oct 23, 2017
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 40 additions & 40 deletions docs/en/guides/testing-SFCs-with-jest.md
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
# Testing Single File Components with Jest
# Tester des composants monofichiers avec Jest

> An example project for this setup is available on [GitHub](https://github.com/vuejs/vue-test-utils-jest-example).
> Un projet exemple pour cette installation est disponible sur [GitHub](https://github.com/vuejs/vue-test-utils-jest-example).
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Un exemple de projet


Jest is a test runner developed by Facebook, aiming to deliver a battery-included unit testing solution. You can learn more about Jest on its [official documentation](https://facebook.github.io/jest/).
Jest est un lanceur de tests développé par Facebook. Il a pour but de procurer une solution complète de tests unitaire. Vous pouvez en apprendre plus sur Jest sur [sa documentation officielle](https://facebook.github.io/jest/).
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unitaires


## Setting up Jest
## Installer Jest

We will assume you are starting with a setup that already has webpack, vue-loader and Babel properly configured - e.g. the `webpack-simple` template scaffolded by `vue-cli`.
On va supposer que vous commencez avec une installation qui a déjà webpack, vue-loader et Babel de correctement configurés (cf. le template `webpack-simple` via `vue-cli`).
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remplace « e.g. » par « par ex. » chaque fois que tu le croise.
De la même manière chaque i.e. que tu croises seront des « c.-à-d. »


The first thing to do is install Jest and `vue-test-utils`:
La première chose à faire est d'installer Jest et `vue-test-utils` :

```bash
$ npm install --save-dev jest vue-test-utils
```

Next we need to define a unit script in our `package.json`.
Ensuite, on doit définir un script dans notre `package.json`.

```json
// package.json
Expand All @@ -25,15 +25,15 @@ Next we need to define a unit script in our `package.json`.
}
```

## Processing SFCs in Jest
## Traiter les composants monofichiers dans Jest

To teach Jest how to process `*.vue` files, we will need to install and configure the `jest-vue` preprocessor:
Pour indiquer à Jest comment traiter les fichiers `*.vue`, on va avoir besoin d'installer et de configurer le pré-processeur `jest-vue` :
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

préprocesseur


``` bash
npm install --save-dev jest-vue
```

Next, create a `jest` block in `package.json`:
Ensuite, créez un objet `jest` dans `package.json` :

``` json
{
Expand All @@ -42,46 +42,46 @@ Next, create a `jest` block in `package.json`:
"moduleFileExtensions": [
"js",
"json",
// tell Jest to handle *.vue files
// indique à Jest de gérer les fichiers *.vue
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

`*.vue`

Tu peux PR l'original si tu le souhaites.

"vue"
],
"transform": {
// process *.vue files with jest-vue
// traite les fichiers *.vue avec jest-vue
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

`*.vue`

".*\\.(vue)$": "<rootDir>/node_modules/jest-vue"
},
"mapCoverage": true
}
}
```

> **Note:** `jest-vue` currently does not support all the features of `vue-loader`, for example custom block support and style loading. In addition, some webpack-specific features such as code-splitting are not supported either. To use them, read the guide on [testing SFCs with Mocha + webpack](./testing-SFCs-with-mocha-webpack.md).
> **Note :** `jest-vue` ne supporte actuellement pas toutes les fonctionnalités de `vue-loader`, par exemple le support des blocks personalisés et du chargement de styles. De plus, quelques fonctionnalités spécifique à webpack comme le découpage du code ne sont pas supportées. Pour les utiliser, lisez le guide sur [tester des composants monofichiers avec Mocha + webpack](./testing-SFCs-with-mocha-webpack.md).

## Handling webpack Aliases
## Gérer les alias webpack

If you use a resolve alias in the webpack config, e.g. aliasing `@` to `/src`, you need to add a matching config for Jest as well, using the `moduleNameMapper` option:
Si vous utilisez un alias de résolution dans la configuration de webpack, c.à.d faire un alias `@` pour `/src`, vous devez aussi ajouter une configuration pour Jest en utilisant l'option `moduleNameMapper` :
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

c.-à-d.


``` json
{
// ...
"jest": {
// ...
// support the same @ -> src alias mapping in source code
// gère le même alias dans le code @ -> src
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

supporte la même concordance d'alias @ -> src dans le code source

"moduleNameMapper": {
"^@/(.*)$": "<rootDir>/src/$1"
}
}
}
```

## Configuring Babel for Jest
## Configurer Babel pour Jest

Although latest versions of Node already supports most ES2015 features, you may still want to use ES modules syntax and stage-x features in your tests. For that we need to install `babel-jest`:
Même si les dernières versions de Node supportent la plupart des fonctionnalités ES2015, vous souhaitez quand même utiliser la syntaxe des modules ES ainsi que les fonctionnalités stage-x dans vos tests. Pour cela, on doit installer `babel-jest` :
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

version de Node.js

PR l'original si tu le souhaites.


``` bash
npm install --save-dev babel-jest
```

Next, we need to tell Jest to process JavaScript test files with `babel-jest` by adding an entry under `jest.transform` in `package.json`:
Ensuite, on doit indiquer à Jest de gérer les fichiers de tests JavaScript avec `babel-jest` en ajoutant une entrée sous `jest.transform` dans `package.json` :

``` json
{
Expand All @@ -90,23 +90,23 @@ Next, we need to tell Jest to process JavaScript test files with `babel-jest` by
// ...
"transform": {
// ...
// process js with babel-jest
// gérer le JavaScript avec babel-jest
"^.+\\.js$": "<rootDir>/node_modules/babel-jest"
},
// ...
}
}
```

> By default, `babel-jest` automatically configures itself as long as it's installed. However, because we have explicitly added a transform for `*.vue` files, we now need to explicitly configure `babel-jest` as well.
> Par défaut, `babel-jest` va automatiquement s'autoconfigurer dès l'installation. Cependant, comme nous avons explicitement ajouté une transformation pour les fichiers `*.vue`, on se doit aussi d'explicitement configurer `babel-jest`.

Assuming using `babel-preset-env` with webpack, the default Babel config disables ES modules transpilation because webpack already knows how to handle ES modules. However, we do need to enable it for our tests because Jest tests run directly in Node.
En assumant que vous utilisez `babel-preset-env` avec webpack, la configuration par défaut de Babel désactive la transpilation des modules ES car webpack sait déjà comment traiter ces modules. Nous devons, cependant, l'activer pour nos tests car, Jest fonctionne directement dans Node.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

En supposant

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nous devons cependant l'activer

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"autoconfigurer"

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

En supposant

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Node.js


Also, we can tell `babel-preset-env` to target the Node version we are using. This skips transpiling unnecessary features and makes our tests boot faster.
On doit aussi indiquer à `babel-preset-env` d'utiliser la version de Node que nous utilisons. Cela empêchera de transpiler inutilement des fonctionnalités et lancera nos tests plus rapidement.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Node.js


To apply these options only for tests, put them in a separate config under `env.test` (this will be automatically picked up by `babel-jest`).
Pour appliquer ces options uniquement aux tests, mettez-les dans un fichier de configuration différent sous `env.test` (cela va être automatiquement être utilisé par `babel-jest`).

Example `.babelrc`:
Exemple `.babelrc`:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

espace avant le « : »


``` json
{
Expand All @@ -123,56 +123,56 @@ Example `.babelrc`:
}
```

### Snapshot Testing
### Test d'instantanés

You can use [`vue-server-renderer`](https://github.com/vuejs/vue/tree/dev/packages/vue-server-renderer) to render a component into a string so that it can be saved as a snapshot for [Jest snapshot testing](https://facebook.github.io/jest/docs/en/snapshot-testing.html).
Vous pouvez utiliser [`vue-server-renderer`](https://github.com/vuejs/vue/tree/dev/packages/vue-server-renderer) pour transformer un composant en une chaîne de caractères afin de le sauvegarder dans un instantané pour [Jest tests d'instantanés](https://facebook.github.io/jest/docs/en/snapshot-testing.html).
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

chaine (graphie rectifiée 1990)


The render result of `vue-server-renderer` includes a few SSR-specific attributes, and it ignores whitespaces, making it harder to scan a diff. We can improve the saved snapshot with a custom serializer:
Le résultat du rendu de `vue-server-renderer` inclut quelques attributs spécifiques au rendu côté serveur. Il ignore les espaces, cela rend plus dur d'analyser une différence. On peut améliorer l'instantané sauvegardé avec un sérialiseur personnalisé :

``` bash
npm install --save-dev jest-serializer-vue
```

Then configure it in `package.json`:
Puis configurez-le dans `package.json`:

``` json
{
// ...
"jest": {
// ...
// serializer for snapshots
// sérialiseur pour les instantanés
"snapshotSerializers": [
"<rootDir>/node_modules/jest-serializer-vue"
]
}
}
```

### Placing Test Files
### Placer les fichiers de tests

By default, jest will recursively pick up all files that have a `.spec.js` or `.test.js` extension in the entire project. If this does not fit your needs, it's possible [to change the testRegex](https://facebook.github.io/jest/docs/en/configuration.html#testregex-string) in the config section in the `package.json` file.
Par défaut, Jest va récursivement récupérer tous les fichier qui ont une extension en `.spec.js` ou `.test.js` dans le projet. Si cela ne correspond pas à vos besoins, il est possible [de changer l'expression régulière testRegex](https://facebook.github.io/jest/docs/en/configuration.html#testregex-string) dans la configuration se trouvant dans `package.json`.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

les fichiers

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

`testRegex`


Jest recommends creating a `__tests__` directory right next to the code being tested, but feel free to structure your tests as you see fit. Just beware that Jest would create a `__snapshots__` directory next to test files that performs snapshot testing.
Jest recommande de créer un répertoire `__tests__` au même niveau que le code testé, mais soyez libre de structurer vos tests selon vos besoins. Soyez juste au courant que Jest créera un répertoire `__snapshots__` au même niveau que les fichiers de tests qui travaillent sur des instantanés.

### Example Spec
### Exemple d'une spécification

If you are familiar with Jasmine, you should feel right at home with Jest's [assertion API](https://facebook.github.io/jest/docs/en/expect.html#content):
Si vous êtes habitué à Jasmine, vous devriez très bien vous en sortir avec [l'API d'assertions de Jest](https://facebook.github.io/jest/docs/en/expect.html#content) :

```js
import { mount } from 'vue-test-utils'
import Component from './component'

describe('Component', () => {
test('is a Vue instance', () => {
describe('Composant', () => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Component

test('est une instance de Vue', () => {
const wrapper = mount(Component)
expect(wrapper.isVueInstance()).toBeTruthy()
})
})
```

### Resources
### Ressources

- [Example project for this setup](https://github.com/vuejs/vue-test-utils-jest-example)
- [Examples and slides from Vue Conf 2017](https://github.com/codebryo/vue-testing-with-jest-conf17)
- [Projet exemple pour cette installation](https://github.com/vuejs/vue-test-utils-jest-example)
- [Exemples et diapositives depuis la Vue Conf 2017](https://github.com/codebryo/vue-testing-with-jest-conf17)
- [Jest](https://facebook.github.io/jest/)
- [Babel preset env](https://github.com/babel/babel-preset-env)