Using with webpack
Jest poate fi utilizat în proiecte care folosesc webpack pentru gestionarea fișierelor statice, stiluri şi compilare. webpack oferă nişte provocări unice față de alte instrumente deoarece se integrează direct cu aplicația voastră pentru a permite gestionarea stilurilor, resurselor statice cum ar fi imagini şi fonturi, împreună cu ecosistemul expansiv de compilare în JavaScript a limbajelor şi instrumentelor.
Un exemplu webpack
Să începem cu un fişier de configurare webpack comun pe care să-l traducem într-o configurare Jest.
module.exports = {
module: {
loaders: [
{exclude: ['node_modules'], loader: 'babel', test: /\.jsx?$/},
{loader: 'style-loader!css-loader', test: /\.css$/},
{loader: 'url-loader', test: /\.gif$/},
{loader: 'file-loader', test: /\.(ttf|eot|svg)$/},
],
},
resolve: {
alias: {
config$: './configs/app-config.js',
react: './vendor/react-master',
},
extensions: ['', 'js', 'jsx'],
modules: [
'node_modules',
'bower_components',
'shared',
'/shared/vendor/modules',
],
},
};
If you have JavaScript files that are transformed by Babel, you can enable support for Babel by installing the babel-jest
plugin. Non-Babel JavaScript transformations can be handled with Jest's transform
config option.
Gestionarea resurselor statice
În continuare, să configurăm Jest să se ocupe de fișierele statice, cum ar fi stilurile şi imaginile. De obicei, aceste fişiere nu sunt deosebit de utile în teste, astfel încât putem liniștiți să le dublăm. Cu toate acestea, dacă utilizaţi module CSS atunci este preferat să dublați un proxy pentru căutările className.
{
"jest": {
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
}
}
}
Şi fișierele dubluri:
module.exports = {};
module.exports = 'test-file-stub';
Dublarea modulelor CSS
Puteți utiliza un ES6 Proxy pentru a mock-ui module CSS:
- npm
- Yarn
npm install --save-dev identity-obj-proxy
yarn add --dev identity-obj-proxy
Apoi toate căutările pentru className pe obiectul de stiluri va fi returnat ca-atare (de exemplu, styles.foobar === 'foobar'
). This is pretty handy for React Snapshot Testing.
{
"jest": {
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|less)$": "identity-obj-proxy"
}
}
}
If moduleNameMapper
cannot fulfill your requirements, you can use Jest's transform
config option to specify how assets are transformed. For example, a transformer that returns the basename of a file (such that require('logo.jpg');
returns 'logo'
) can be written as:
const path = require('path');
module.exports = {
process(sourceText, sourcePath, options) {
return {
code: `module.exports = ${JSON.stringify(path.basename(sourcePath))};`,
};
},
};
{
"jest": {
"moduleNameMapper": {
"\\.(css|less)$": "identity-obj-proxy"
},
"transform": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/fileTransformer.js"
}
}
}
I-am specificat lui Jest să ignore fişiere de stil sau imagini, şi în schimb, să includă fișierele noastre mock. Puteţi ajusta expresia regulată pentru a se potrivi tipurilor de fișiere pe care configuratia voastră webpack o gestionează.
tip
Remember to include the default babel-jest
transformer explicitly, if you wish to use it alongside with additional code preprocessors:
"transform": {
"\\.[jt]sx?$": "babel-jest",
"\\.css$": "some-css-transformer",
}
Configurarea Jest pentru a găsi fişierele noastre
Now that Jest knows how to process our files, we need to tell it how to find them. Pentru opțiunile webpack modulesDirectories
, şi extensions
exista opțiuni analoage în Jest respectiv moduleDirectories
şi moduleFileExtensions
.
{
"jest": {
"moduleFileExtensions": ["js", "jsx"],
"moduleDirectories": ["node_modules", "bower_components", "shared"],
"moduleNameMapper": {
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js",
"\\.(gif|ttf|eot|svg)$": "<rootDir>/__mocks__/fileMock.js"
}
}
}
Note:
<rootDir>
is a special token that gets replaced by Jest with the root of your project. Most of the time this will be the folder where yourpackage.json
is located unless you specify a customrootDir
option in your configuration.
Similarly, webpack's resolve.root
option functions like setting the NODE_PATH
env variable, which you can set, or make use of the modulePaths
option.
{
"jest": {
"modulePaths": ["/shared/vendor/modules"],
"moduleFileExtensions": ["js", "jsx"],
"moduleDirectories": ["node_modules", "bower_components", "shared"],
"moduleNameMapper": {
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js",
"\\.(gif|ttf|eot|svg)$": "<rootDir>/__mocks__/fileMock.js"
}
}
}
And finally, we have to handle the webpack alias
. For that, we can make use of the moduleNameMapper
option again.
{
"jest": {
"modulePaths": ["/shared/vendor/modules"],
"moduleFileExtensions": ["js", "jsx"],
"moduleDirectories": ["node_modules", "bower_components", "shared"],
"moduleNameMapper": {
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js",
"\\.(gif|ttf|eot|svg)$": "<rootDir>/__mocks__/fileMock.js",
"^react(.*)$": "<rootDir>/vendor/react-master$1",
"^config$": "<rootDir>/configs/app-config.js"
}
}
}
Asta e tot! webpack este un instrument complex și flexibil, astfel încât va trebui probabil să faceți unele ajustări care să cuprindă nevoile specifice aplicației voastre. Din fericire pentru cele mai multe proiecte, Jest ar trebui să fie mai mult decât suficient de flexibil pentru a gestiona configurarea voastră webpack.
Notă: Pentru configuraţii webpack mai complexe, ați putea fi interesați să investigați proiecte cum ar fi: babel-plugin-webpack-loaders.
Folosind webpack 2
webpack 2 oferă suport nativ pentru module ES. However, Jest runs in Node, and thus requires ES modules to be transpiled to CommonJS modules. As such, if you are using webpack 2, you most likely will want to configure Babel to transpile ES modules to CommonJS modules only in the test
environment.
{
"presets": [["env", {"modules": false}]],
"env": {
"test": {
"plugins": ["transform-es2015-modules-commonjs"]
}
}
}
Note: Jest caches files to speed up test execution. If you updated .babelrc and Jest is still not working, try running Jest with
--no-cache
.
If you use dynamic imports (import('some-file.js').then(module => ...)
), you need to enable the dynamic-import-node
plugin.
{
"presets": [["env", {"modules": false}]],
"plugins": ["syntax-dynamic-import"],
"env": {
"test": {
"plugins": ["dynamic-import-node"]
}
}
}
Pentru un exemplu de utilizare Jest cu Webpack, React, Redux şi Node, puteți vedea aici.