React unit Test-18-like weapons to battle, environment construction
A complete, excellent project is often inseparable from unit testing, on GitHub on the mainstream front-end projects, basically have the corresponding unit test module.
As far as the React project is concerned, a complete set of unit tests can be used to alert you in the event of a regression error in subsequent iterations, but given the specificity of React itself, we often combine it with tools such as Webpack, and the deployment of unit tests is much more frustrating than regular projects.
This article will be the beginning of the React Unit Test series, and we'll build the environment for the unit tests together.
You can download the sample in my warehouse to this article.
File organization and Configuration
1. Directory structure
We create a new SRC and test folder under the project root, which is used to store each React component module we write, and the latter to store the corresponding unit test module.
Then we need a most essential Package.json file that describes the project's information and dependency module, which executes in the root directory.
NPM Init
The division then enters the relevant information (you can also go all the way back, and then modify), can be automatically generated Package.json.
We then installed the two modules--react and react-dom required for React with NPM:
NPM Install--save-dev react react-dom
By the way, React in v0.14 began to split the React module into the above two packages, wherein the React module contains React.createelement, React.createclass and other api,react-dom modules include R Eactdom.render and other APIs(more specifically can be poked here to understand).
After the installation is complete, the root directory generates the folder node_modules for each NPM module, and the directory structure we see now is this, simple:
2. Webpack Configuration
We intend to follow the mainstream to write script modules in the form of ES6, while the new version of React has also transferred the JSX conversion rights to tools such as Babel, so we intend to configure the loader and packaging in the form of Webpack.
If you don't know webpack, please take a look at this introductory article.
First install Webpack via NPM (the installation of subsequent modules is no longer mentioned):
NPM Install--save-dev Webpack
We want to build an extremely simple test environment, so we just need a very simple webpack configuration, so we create a new webpack.config.js directly in the root directory:
var webpack = require (' Webpack '); module.exports = { entry:undefined, output: { pathinfo:true }, Module: { //loader config loaders: [ {test:/\.js$/, Loader: ' Babel-loader '} ] };
Note that we intend to configure a babel-loader for all. js files to convert JSX and ES6, so remember to install Babel-loader via NPM.
3. Karma Configuration
A good test tool can greatly improve your productivity, and as the angular team produced karma is the outstanding and most popular test tool, it has the following features:
1. Cli running, webstorm with perfect 2. Good support for Mocha, Jasmine and other test framework 3. Support for multi-browser test 4. Good ecology, more than 5 plug-ins. Integrated Monitoring free hands, auto-start when file changes, similar to gulp watch function
Note that the Karma installation is best installed in a global manner to ensure normal use of the Karma CLI functionality (we will perform the test in the form of Karma XXX later):
NPM Install Karma-g
Next we create a new karma.conf.js configuration file in the root directory:
var IsCI = Process.env.CONTINUOUS_INTEGRATION = = = ' true '; var webpackconfig = require ('./webpack.config.js '); Module.exports = function (config) { config.set ({ basepath: ', files: [ ' Test/*.js ' ], Preprocessors: { ' test/*.js ': [' Webpack ' }, webpack:webpackconfig, webpackmiddleware: { Noinfo:true }, port:9876, colors:true, autowatch:true, singlerun:isci });};
Where the IsCI variable is used to determine whether the current system environment has default support for continuous integration (through the environment variable continuous_integration judgment, the specific CI variable name or value is based on the specific circumstances, such as Vuejs used in the Ci_pull_ REQUEST), set the Singlerun to False if the CI is not turned on.
In addition, we made a definition in preprocessors, requiring that the script in the test directory be executed by Webpack preprocessing (JSX, ES6), and the Webpack configuration item is set to the configuration of the Webpack.config.js.
We're going to use mocha as a framework for unit testing (you can also use Jasmine, of course), and then use PHANTOMJS as the test browser engine.
So first install the Karma plugin of these two modules through NPM package:
NPM Install--save-dev Karma-mocha karma-phantomjs-launcher
Then we further configure the Karma.conf.js:
var IsCI = Process.env.CONTINUOUS_INTEGRATION = = = ' true '; var webpackconfig = require ('./webpack.config.js '); Module.exports = function (config) {config.set ({basepath: ", Frameworks: [' Mocha ', ' Phanto MJs '], files: [' Test/*.js '], preprocessors: {' test/*.js ': [' Webpack ' ]}, Webpack:webpackconfig, Webpackmiddleware: {noinfo:true}, port:9876 , Colors:true, Autowatch:true, browsers: [' Phantomjs ', ' Phantomjs_custom '], customlaunchers: {//Custom browser launcher ' Phantomjs_custom ': {base: ' Phantomjs ', options: { Windowname: ' My-window ', settings: {websecurityenabled:false }}, Flags: ['--load-images=true '], debug:true}} , Phantomjslauncher: { Resource (such as Test module) is still phantom not quit Exitonresourceerror:true} When error occurs, singlerun:isci});
At this point, we first pretended that the configuration has been exhausted (in fact, not yet), the following is the new test module
4. Create a test module
Now that there are no React components in the SRC directory, we create a alert.js:
Import React from ' React '; const Alert = React.createclass ({ render () { return ( <div {...this.props}> {This.props.children} </div> );} ); Export default Alert;
Next, a new Alert.js file is added to the test directory for simple unit testing of the Src/alert.js components described above:
Import React from ' React ', import reacttestutils from ' react/lib/reacttestutils ', import Alert from '. /src/alert ';d escribe (' Alert ', () = { It (' Insert a section with a strong tag into the page ', () = = {Let instance = Reacttestutils.renderintodocument ( <Alert> <strong>Message</strong> </alert > ); Assert.ok (Reacttestutils.findrendereddomcomponentwithtag (instance, ' strong '));}) ;
As shown in the code above, we assume that a <strong> tag is placed in the <Alert> component and rendered to the page (here react/lib/reacttestutils is what we'll cover in the next article).
So we assert that there must be a <strong> tag in the Alert component on the page that is mounted on this form, and that if the <strong> tag is not found, the unit test fails.
Now we seem to have basically completed the entire configuration, perform Karma start unit test take a look:
Karma Start--browsers Phantomjs_custom
Will find an error:
This is a pit of PHANTOMJS.--PHANTOMJS does not support Function.prototype.bind, details are visible in this issue.
The workaround is also simple, replace the KARMA-PHANTOMJS with the Karma-phantomjs-shim.
After installing Karma-phantomjs-shim with NPM We modify the frameworks configuration item in the Karma.conf.js:
Frameworks: [ ' Mocha ', ' Phantomjs-shim ' ],
Then re-execute the Karma and notice that the error continues to be duly completed:
This is because Karma eventually runs the unit test in a client browser instead of node, and our test module does not have a require (' assert ') reference, and the client naturally does not get the Assert object.
The workaround is to use Karma-chai to further modify the frameworks configuration items in the Karma.conf.js, plus the Chai plugin, after installing with NPM:
Frameworks: [ ' Mocha ', ' chai ', ' Phantomjs-shim ' ],
Then execute the karma:
666 of ~ So far all our configurations are tossing and finishing. You can use this scenario later to make simple unit tests of all the components in the SRC directory ~ more interesting configurations or tools we'll introduce in the next article.
At the end of the note, the example of this article can be downloaded from my warehouse and interested readers can download their own research ~ Mutual Encouragement ~
Unit Test react