Introduction
This manual contains a description of useful and the most frequently used front-end tools. The process of installing tools and the main points of working with them are described here.
NPM
Introduction
Third-party libraries and plugins are often added during project development. As a result, developers need to search for the required dependency, download, unpack the archive and copy files to the project. Package managers help make this routine work automated.
Package Manager is software that allows managing processes of installation, removal, configuration and update of various components.
Attachment of third-party libraries by the package manager is replaced with a pair of commands in the terminal.
NPM is one of the package managers used in frontend projects.
npm (Node.js Package Manager) is the package manager that is part of Node.js. It is used to download packages from the cloud-based npm server or to download packages to this server.
Official website
Start of work
For installing npm it is needed to download and instal NodeJS (npm will be installed automatically): https://nodejs.org/en/.
Implementation
Packages installation
A package is one or several JavaScript files representing some library or tool. The following command should be done for package installation:
npm install <package name>
The key -g is used for global package installation. The package with source codes is located in the directory node_modules/ after installation.
Version check
The following command is run to check the current version of npm:
npm -v
Configuration file adjustment
The package.json file contains information about the application such as: name, version, dependencies, etc. Any directory containing this file is interpreted as a Node.js package.
Example of package.json file:
To create the package.json file, run the following command:
npm init
After that, it is necessary to fill some information about the project.
This file contains names and versions of all packages required in the project. Using npm install command, all packages of package.json can be loaded.
For installing some package and saving it automatically in package.json file, the following command is used:
npm install <package name> –save-dev
Alternatives
Yarn
Official website https://classic.yarnpkg.com/en/
Yarn is a package manager jointly created by Facebook, Google, Exponent and Tilde. Its goal is solving a number of problems that the developers have faced during using npm:
- packages installation was not enough fast and consistent;
- security issues occurred, because npm allows packages to run code while installation.
Bower
Official website https://bower.io/
Bower is a package management system on the client side. Its work depends on Node.js and npm. Bower system is meant to manage components that contain HTML, CSS, JavaScript, fonts and images. It contains functions for searching, downloading and installing packages. Bower.json manifest file is designed to manage packages in Bower.
GulpJS
Introduction
Building is an integral part of any frontend project. Task managers are used for this task.
Task manager is an application designed to automate project building and for other routine tasks that should be performed during the development process (code minimization, concatenation, launch of unit tests and much more). To do this, the developer writes instruction to task performance after creating a task-file. As a result, the project development is simplified.
GulpJS is one of these task managers.
GulpJS is a task manager for automatic performance of frequently used tasks, it is written in JavaScript. This software uses the command line to run tasks defined in Gulpfile file. It is created as a branch of Grunt project to take best practices out of it. It is distributed through the NPM package manager, licensed under MIT.
GulpJS differs from other task managers by better visibility and simplicity. It is also the fastest project builder.
There are about 3000 plugins for Gulp by 2017.
Official website
Features
- Creating web server and automatic page reload in browser during code saving, tracking changes in project files.
- Using various JavaScript, CSS and HTML preprocessors (CoffeeScript, Less, Sass, Stylus, Jade, etc.).
- Minifying CSS and JS code, and also optimizing and concatenating separate project files into one.
- Creating vendor prefixes automatically for CSS (addings before CSS property name that browser manufacturers add for non-standard properties).
- Managing files and folders within the project, such as creating, deleting, renaming.
- Running and monitoring external commands in execution of the operating system.
- Working with images, such as compression, creating sprites, resizing (png, jpg, svg, etc.).
- Deploying (sending to an external server) of the project via FTP, SFTP, etc.
- Connecting and using an infinitely large number of Node.js and Gulp utilities, programs and plug-ins in the project.
- Creating of various project maps and automating of other manual labor.
Start of work
NodeJS and npm should be installed in the system.
Step 1: For a global installation of GulpJS using the npm batch manager, run the following command:
npm install gulp -g
Step 2: It should be installed for the following application:
npm install –save-dev gulp
Step 3: Next, the file gulpfile.js should be created in the root of the project (in this file, building tasks are written).
Load of additional plugins, that can be used for project building, is also done using npm by the following command:
npm install <plugin name> –save-dev
All installed plugins are located in node_modules/ directory.
Example gulpfile.js
Implementation
Step 1: First, gulp should be connected to the project. To perform this, in the file gulpfile.js the following line should be written:
var gulp = require(‘gulp’);
Require() function allows connecting plugins from the node_modules/ directory.
Step 2: Using gulp variable, tasks for project building can be created:
gulp.task(‘exampleTask’, function() {});
The task method takes two values: the name and the function with the task body. This instruction can be already performed. To do this, the following line should be written in the console:
gulp exampleTask
Basic Commands
The more complex example of the instruction is given below:
gulp.task('exampleTask', function () {
return gulp.src('source-files')
.pipe(plugin())
.pipe(gulp.dest('folder'));
});
Commands used in this example:
- gulp.src – selection of source project files for plugin processing;
- pipe(plugin()) – calling Gulp plugin for file processing;
- pipe(gulp.dest(‘folder’)) – an output of the resulting file to the destination folder.
Masks of files
The gulp.src function takes a file mask as a value. Examples of masks:
- ./ – the current directory;
- ../ – the parent directory;
- js/index.js – the file index.js in the js folder;
- js/*.js – all files with js extension in js folder;
- js/**/*.js – all files with js extension in js folder and its subdirectories;
- !js/*.js – excluding files with js extension in js folder.
Streams
Using streams is one of the most important advantages of GulpJS.
Streams allow transferring some data in sequence from one function to another, and each performs some actions with this data.
The function gulp.src() creates a stream of objects representing files that are passed to it as a parameter. Next, using pipe functions, a pipeline is built, by which the stream of objects is transferred. The plugin, which in some way processes the stream of objects, is passed as a parameter to this function.
Below there is an example of using streams. In this example, third-party plugins gulp-jshint and gulp-concat are used, which should be installed and connected to gulpfile.js.
The function gulp.src takes files by the mask js/*.js. It starts JSHint and prints the result. Then it concatenates files and at the end stores the received file after concatenating in the dist/. directory.
gulp.task('example', function () {
return gulp.src('js/*.js')
.pipe(jshint())
.pipe(concat('index.js'))
.pipe(gulp.dest('dist'));
});
Third-party plugins
Let’s consider an example of using third-party plugins. To do this, the instruction for js files concatenating is created:
Step 1: First, you need to connect the plugin with require command:
var concat = require(‘gulp-concat’);
Step 2: Then the task to concatenate the files with js extension located in js/ directory should be created. Finally, the received file is placed in dist/js directory:
gulp.task('concat', function () {
return gulp.src('js/*.js')
.pipe(concat('index.js'))
.pipe(gulp.dest('dist/js'));
});
Step 3: Further this task can be done in the console:
gulp concat
Additional information
Also the task that causes the execution of other tasks can be defined.
gulp.task(‘build’, [‘html’, ‘css’]);
Plus, there is a watch method for watching changes in files:
gulp.watch(‘file mask for watching’, [‘a task name, which is done during files changing’]);
A default task can be created in gulpfile.js :
gulp.task(‘default’, [‘task1’, ‘task2’]);
This task is launched from the console by using the command:
gulp
Basic Plugins
- gulp-autoprefixer – automatically sets prefixes to CSS properties;
- gulp-browser-sync – creates a connection, then performs page auto-updating when client or even server files are changed;
- gulp-uncss – for an optimization of CSS files. The plugin analyzes HTML code and finds all unused and duplicated styles;
- gulp-csso – CSS minifier;gulp-htmlmin – a simple HTML-style minifier;
- gulp-htmlhint – HTML validator;gulp-uglify – JavaScript minifier;
- gulp-concat – files concatenation;
- gulp-webserver – allows creating and running server;gulp-jshint – checking JS code quality;
- gulp-jasmine – running jasmine tests;
- gulp-jsdoc – for generation of JSDoc documentation.
The full list of Gulp plugins can be found here:
Alternatives
GruntJS
https://gruntjs.com/ is an official website
GruntJS is a task manager, like GulpJS, which allows automating routine tasks for developers related to code minification, code quality analysis, testing, and many others.
Differences
Unlike GulpJS, GruntJS does not use data streaming. Gruntfile (the configuration file in GruntJS) is less readable, and it is harder to take it up than the configuration file in GulpJS. In addition, GruntJS is a slower assembler than Gulp.
Jasmine
Introduction
Testing is part of the development process on any project. It allows verifying the code correctness and identifying situations where program behavior is incorrect, undesirable or doesn’t conform to the specification. Each engineer checks whether some function works correctly during the development process. The easiest way to do this is to run the function and see a result. However, this approach is a very imperfect way of code testing. As a result, any moment that leads to malfunctioning can be missed and thus to an error. Automated testing is used to prevent such situations.
Automated testing is the process of writing tests separately from the code, with the ability to run them at any time and check all important usage cases.
One of the tools for testing JavaScript code is Jasmine.
Jasmine is a BDD framework for testing JavaScript code, which borrowed many features from RSpec.
Official website
Features
- A support of asynchronous testing.
- An ability to expose observers on different objects.
Start of work
To connect Jasmine to the project, download the library and connect the following files to the main HTML page:
- lib/jasmine-*/jasmine.js – the framework itself;
- lib/jasmine-*/jasmine-html.js – the presentation of results in HTML form;
- lib/jasmine-*/jasmine.css – the appearance of the test result;
- SpecRunner.html – the file that should be opened in a browser to run the tests.
Synchronization with tools
GulpJS
Jasmine can be connected to the project build in GulpJS:
Step 1: First, the plugin gulp-jasmine should be installed:
npm install gulp-jasmine –save-dev
Step 2: Then the plugin in the build file should be connected and tests starting task should be created:
var jasmine = require('gulp-jasmine');
gulp.task('jasmine', function() {
gulp.src('tests files')
.pipe(jasmine());
});
KarmaJS
(the working process with this tool is described in detail at the end of the article)
To connect Jasmine to KarmaJS the following steps should be done:
Step 1: Install KarmaJS:
npm install -g karma-cli
Step 2: Install the plugins required to run tests written in Jasmine in Chrome and PhantomJS browsers:
npm install karma-jasmine karma-chrome-launcher karma-phantomjs-launcher
Step 3: Install Jasmine:
npm install -g jasmine
Step 4: Connect plugins and set the path to tests in the karma configuration file.
Implementation
Keywords
- describe – the definition of the test set;
- it – test definition;
- expect – defining the expectations, that are checked in the test.
Describe and it functions take two parameters: the first is the name, the second is the function with the code.
An example of a basic test
describe(“test suite name”, function () {
it(“test name”, function () {
expect(2+2).toBe(4);
});
});
Results verifying methods
- expect().toBe() – verifying variables for equality (‘===’);
- expect().not.toBe() – verifying variables for equality (‘! ==’);
- expect().toEqual() – verifying equality of variables and objects, including content;
- expect().toBeDefined() – verifying existence;
- expect().toBeUndefined() – verifying nonexistence;;
- expect().toBeNull() – verifying value of the variable to null;
- expect().toBeTruthy() – verifying validation;
- expect().toBeFalsy() – verifying falsity;
- expect().toBeLessThan() -verifying the value should be less than;
- expect().toBeGreaterThan() – verifying the value should be bigger than;
- expect().toBeCloseTo() – verifying the value should be close to a number;
- expect().toMatch() – verifying correspondence to a regular expression;
- expect().toContain() – verifying content in the array;
- expect().toThrow() – test exception call;
- expect().toHaveBeenCalled() – check function call.
Additional functions
BeforeEach/afterEach functions are implemented to avoid copying any logic used in the tests. They run accordingly before/after each test.
Runs and waitsFor functions are used for testing asynchronous calls.
- runs – takes an asynchronous function to implement;
- waitsFor – takes three parameters: the first one is the function that should return true if the asynchronous call in runs function was executed, the second one is the error message, the third call is waiting in milliseconds.
describe(“an example of asynchronous call ”, function () {
var result = 0;
function asyncFunc() {
setTimeout(function() { result = result + 2; }, 500);
}
it(“test name”, function () {
runs(function () {
asyncFunc();
});
waitsFor(function() { return result === 2; }, “value didn’t change”, 2000);
});
});
Watchers
The ability to track functions call is implemented by spyOn. This function takes two parameters: the first is the object for which the function is called, the second is the name of the function to be tracked.
if(“verifying functions call”, function () {
spyOn(exampleObject, 'exampleFunction');
exampleObject.exampleFunction();
expect(exampleObject.exampleFunction).toHaveBeenCalled();
});
During testing by spyOn, the number of calls can be tracked, their parameters and each call individually.
To create a function without implementation, createSpy can be used. CreateSpy function takes the function name for identification.
if(“verifying functions call”, function () {
var example = createSpy('EXAMPLE');
example(“param1”, “param2”);
expect(example.identify).toHaveBeenCalledWith(“param1”, “param2”);
expect(example.calls.length).toEqual(1);
});
Creating a mock object is done using createSpyObj. As parameters createSpyObj takes an object name and an array of strings that is a list of mock object methods.
Alternatives
Mocha
https://mochajs.org/ – official website
Mocha is a framework for testing JavaScript code, running on the basis of node.js. It supports work with browsers and asynchronous testing. It provides information about the degree of tests covering.
Chai
https://www.chaijs.com/– official website
Chai is a BDD/TDD assertions library for NodeJS and browser that can be easily implemented in conjunction with any JavaScript testing framework.
QUnit
https://qunitjs.com/– official website
QUnit is a library for JQuery developers, which allows writing unit tests for JavaScript code. It is the official tool for testing jQuery.
ZombieJS
http://zombie.js.org/ – official website
ZombieJS is a lightweight framework for testing JavaScript code. It simulates a browser behavior.
SinonJS
https://sinonjs.org/ – official website
SinonJS is a mock library for JavaScript, which can be used in any test framework.
JSDoc
Introduction
Documentation is the necessary stage in creating a quality product.
Documenting code is the process of describing functions, classes, methods using certain comments in the code, which makes the work with it easier in the future, both for the author and other programmers.
A well-documented project helps new developers understand the project better and quickly, and amplifies control over its individual parts.
One of the JavaScript code documentation tools is JSDoc.
JSDoc is a documentation generator from source code comments in JavaScript. The syntax of JSDoc is similar to Javadoc, which is used for Java code documentation. Generated documentation is in HTML format.
Official website
Implementation
The documentation is generated from the source code comments.
Comments start with a slash of two asterisks (/**) and end with a slash asterisk (*/). Each new line in the comment starts with an asterisk (*).
The text of the documentation description is placed in this construction.
Inside the comment, tags can be used. Each tag begins with @.
Tags
- @author – Developer’s name;
- @constructor – Indicates that the function is used as a constructor;
- @deprecated – Indicates an out-of-date or not recommended function;
- @description – Specifies function description;
- @exception – Describes the exception;
- @param – Describes the function parameter (type is specified in curly brackets);
- @private – Indicates the private method;
- @property -Specifies information about the property in the object;
- @return – Describes a return value;
- @see – Describes connection with another object;
- @summary – Specifies description for a function, like@description;
- @this – Specifies a type of the object pointed to by this within the function;
- @throw – Describes exception (type is specified in curly brackets);
- @type – Specifies a type of variable (type is specified in curly brackets);
- @typedef – Specifies a custom type (type is specified in curly brackets);
- @version – Specifies a version of library.
An example
/**
* @description Two numbers summing function.
* @param {number} a - The first number.
* @param {number} b - The second number.
* @return {number}
*/
function sum(a, b) {
return a + b;
}
Generation of documentation
Generation of documentation can be done using GulpJS. Plugin gulp-jsdoc is used for this. The plugin installation is:
npm install gulp-jsdoc –save-dev
The next step is to plug in the plugin in gulpfile.js:
var jsdoc = require(‘gulp-jsdoc’);
The task to generate the documentation is created:
gulp.task('jsdoc', function () {
gulp.src('source-files')
.pipe(jsdoc());
});
Alternatives
YUIDoc
http://yui.github.io/yuidoc/ – official website
YUIDoc is a NodeJS application that is used to generate documentation from comments with syntax similar to Javadoc and Doxygen. This tool provides:
- “Live preview”.
- Support of different programming languages.
Docco
http://ashkenas.com/docco/ – official website
Docco is a documentation generator written in CoffeeScript Literate. Documentation Docco is a html page, where both source code and description text are represented.
KarmaJS
Introduction
There are a lot of different tools that simplify the project development. A utility like KarmaJS is used to simplify the testing process of the project.
KarmaJS is a console tool that allows running tests in different browsers, tracking changes in the source code by running tests automatically and allows determining the coverage percentage.
Official website
https://karma-runner.github.io/1.0/index.html
Features
- Running tests from the console.
- An automatic tests start after each change of the source code.
- A support of various frameworks for testing (jasmine, mocha, qunit, etc.).
- An ability of testing in several browsers.An ability to integrate with Jenkins.
- Displaying degree of tests coverage.
Start of work
Several dependencies should be installed to get started with KarmaJS.
Installation is performed using the npm package manager.
It is also necessary for working with KarmaJS.
Step 1: First you need to install KarmaJS:
npm install -g karma-cli
Step 2: Next, the emulator should be installed to test JavaScript code:
npm install -g phantomjs
Step 3: Then the necessary plug-ins should be installed to run tests in the required browsers. There are the following plug-ins for automatically opening browsers when running tests:
- karma-chrome-launcher – Chrome;
- karma-firefox-launcher – Mozilla Firefox;
- karma-safari-launcher – Safari.
Implementation
Step 1: A configuration file should be firstly created to organize the tests launch in KarmaJS. The following command is run to perform this:
karma init
This command will ask you to fill in some information about KarmaJS configuration, including information about the browsers where testing will be performed, tests location and other.
Step 2: Next the configuration file should be configured.
Parameters
- files() – list of files to download;
- exclude() – list of file exceptions from files();
- reporters() – list of plug-ins used for displaying test results;
- port() – the port of the web server;
- runnerPort() – client’s port;
- colors() – enable / disable colors when logging to the console;
- logLevel() – logging format;
- autoWatch() – enable / disable automatic start of tests when source code changes;
- browsers() – the list of browsers in which tests will be run (Chrome, Firefox, Safari, PhantomJS);
- captureTimeout() – setting the timeout in milliseconds;singleRun()- for one-time start;
- preprocessors() – list of handlers applied to files, before downloading to the browser.
Tests coverage degree
To add displaying of the degree of tests coverage in KarmaJS the following steps should be done:
Step 1: To add a mask of files in parameter preprocessors, the degree of which should be checked:
preprocessors: { ‘js/*.js’: [‘coverage’] }
Step 2: To add the ‘coverage’. line to the reporter’s parameter.
Step 3: To add the parameters of the degree of tests coverage:
coverageReporter: { type: ‘text’ }
Code quality checking
To verify the quality of the code in KarmaJS it is necessary:
Step 1: To set Jshint dependency:
npm install jshint –save-dev
Step 2: To add a mask of files which code quality should be checked into preprocessors parameter:
preprocessors: { ‘js/*.js’: [‘jshint’] }
Example file karma.conf.js
Tests run
karma start