-
Notifications
You must be signed in to change notification settings - Fork 2
Guide: common-tips.md #9
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
Changes from 1 commit
ee24d71
ae64c7a
5410a4a
a6a2c73
b433d37
e2823d4
6a23cff
dded37e
f63fabc
918c75f
5fe5c9d
441f7f3
bb16ac3
29ba196
c9b5def
54f1306
8973cc3
2b91c43
a47e5ec
81c9a3a
f2bdcb1
3e82d3e
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
- Loading branch information
There are no files selected for viewing
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). | ||
|
||
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/). | ||
|
||
## 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`). | ||
|
||
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 | ||
|
@@ -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` : | ||
|
||
``` 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 | ||
{ | ||
|
@@ -42,46 +42,45 @@ 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 | ||
"vue" | ||
], | ||
"transform": { | ||
// process *.vue files with jest-vue | ||
// traite les fichiers *.vue avec jest-vue | ||
".*\\.(vue)$": "<rootDir>/node_modules/jest-vue" | ||
}, | ||
"mapCoverage": true | ||
} | ||
} | ||
``` | ||
> **Note :** `jest-vue` ne supporte actuellement pas toutes les fonctionnalités de `vue-loader`, par exemple le support des blocs 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). | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. "personnalisés" There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. "spécifiques" |
||
|
||
> **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). | ||
## Gérer les alias webpack | ||
|
||
## Handling webpack Aliases | ||
|
||
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` : | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
"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` : | ||
|
||
``` 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 | ||
{ | ||
|
@@ -90,23 +89,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 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. "gérer" |
||
"^.+\\.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'auto-configurer 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`. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. "s'autoconfigurer" |
||
|
||
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. | ||
|
||
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. | ||
|
||
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`). | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. "mettez-les" |
||
|
||
Example `.babelrc`: | ||
Exemple `.babelrc`: | ||
|
||
``` json | ||
{ | ||
|
@@ -123,56 +122,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). | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. "chaine" -> graphie rectifiée |
||
|
||
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`: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. "configurez-le" |
||
|
||
``` json | ||
{ | ||
// ... | ||
"jest": { | ||
// ... | ||
// serializer for snapshots | ||
// serialiseur pour les instantanés | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. "sérialiseur" |
||
"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`. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. "tous les fichiers" |
||
|
||
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' | ||
import Composant from './composant' | ||
|
||
describe('Component', () => { | ||
test('is a Vue instance', () => { | ||
const wrapper = mount(Component) | ||
describe('Composant', () => { | ||
test('est une instance de Vue', () => { | ||
const wrapper = mount(Composant) | ||
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) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
"préprocesseur"