Tuesday, December 27, 2016

A Node.js Guide to Actually Doing Integration Tests

Integration tests aren’t something that should be dreaded. They are an essential part of having your application fully tested.
When talking about testing, we usually think of unit tests where we test a small chunk of code in isolation. However, your application is larger than that small chunk of code and almost no part of your application works in isolation. This is where integration tests prove their importance. Integration tests pick up where unit tests fall short, and they bridge the gap between unit tests and end-to-end tests.
A Node.js Guide to Actually Doing Integration Tests
You know you need to write integration tests, so why aren’t you doing it?
In this article, you’ll learn how to write readable and composable integration tests with examples in API-based applications.
While we’ll use JavaScript/Node.js for all code examples in this article, most ideas discussed can be easily adapted to integration tests on any platform.

Unit Tests vs Integration Tests: You Need Both

Unit tests focus on one particular unit of code. Often, this is a specific method or a function of a bigger component.
These tests are done in isolation, where all external dependencies are typically stubbed or mocked.
In other words, dependencies are replaced with pre-programmed behavior, ensuring that the test’s outcome is only determined by the correctness of the unit being tested.
You can learn more about unit tests here.
Unit tests are used to maintain high-quality code with good design. They also allow us to easily cover corner cases.
The drawback, however, is that unit tests can’t cover the interaction between components. This is where integration tests become useful.

Integration Tests

If unit tests are defined by testing the smallest units of code in isolation, then integration tests are just the opposite.
Integration tests are used to test multiple, bigger units (components) in interaction, and can sometimes even span multiple systems.
The purpose of integration tests is to find bugs in the connections and dependencies between various components, such as:
  • Passing invalid or incorrectly ordered arguments
  • Broken database schema
  • Invalid cache integration
  • Flaws in business logic or errors in data flow (because testing is now done from broader view).
If the components we’re testing don’t have any complicated logic (e.g. components with minimal cyclomatic complexity), integration tests will be far more important than unit tests.
In this case, unit tests will be used primarily to enforce a good code design.
While unit tests help ensure that functions are properly written, integration tests help ensure that the system is working properly as a whole. So both unit tests and integration tests each serve their own complementary purpose, and both are essential to a comprehensive testing approach.
Unit tests and integration tests are like two sides of the same coin. The coin is not valid without both.
Therefore, testing isn’t complete until you’ve completed both integration and unit tests.

Set up the Suite for Integration Tests

While setting up a test suite for unit tests is pretty straightforward, setting up a test suite for integration tests is oftentimes more challenging.
For example, components in integration tests can have dependencies that are outside the project, like databases, file systems, email providers, external payment services, and so on.
Occasionally, integration tests need to use these external services and components, and sometimes they can be stubbed.
When they are needed, it can lead to several challenges.
  • Fragile test execution: External services can be unavailable, return an invalid response, or be in an invalid state. In some cases, this may result in a false positive, other times it may result in a false negative.
  • Slow execution: Preparing and connecting to external services can be slow. Usually, tests are run on an external server as a part of CI.
  • Complex test setup: External services need to be in the desired state for testing. For example, the database should be preloaded with the requisite test data, etc.

Directions To Follow While Writing Integration Tests

Integration tests don’t have strict rules like unit tests. Despite this, there are some general directions to follow when writing integration tests.

Repeatable Tests

Test order or dependencies shouldn’t alter the test result. Running the same test multiple times should always return the same result. This can be difficult to achieve if the test is using the Internet to connect to third-party services. However, this issue can be worked around through stubbing and mocking.
For external dependencies that you have more control over, setting up steps before and after an integration test will help ensure that the test is always run starting from an identical state.

Testing Relevant Actions

To test all possible cases, unit tests are a far better option.
Integration tests are more oriented on the connection between modules, hence testing happy scenarios is usually the way to go because it will cover the important connections between modules.

Comprehensible Test and Assertion

One quick view of the test should inform the reader what is being tested, how the environment is setup, what is stubbed, when the test is executed, and what is asserted. Assertions should be simple and make use of helpers for better comparison and logging.

Easy Test Setup

Getting the test to the initial state should be as simple and as understandable as possible.

Avoid Testing Third-Party Code

While third-party services may be used in tests, there’s no need to test them. And if you don’t trust them, you probably shouldn’t be using them.

Leave Production Code Free of Test Code

Production code should be clean and straightforward. Mixing test code with production code will result in two non-connectable domains being coupled together.


Relevant Logging

Failed tests aren’t very valuable without good logging.
When tests pass, no extra logging is needed. But when they fail, extensive logging is vital.
Logging should contain all database queries, API requests and responses, as well as a full comparison of what is being asserted. This can significantly facilitate debugging.

Good Tests Look Clean and Comprehensible

A simple test that follows the guidelines herein could look like this:
const co = require('co'); 
const test = require('blue-tape'); 
const factory = require('factory');
const superTest = require('../utils/super_test');
const testEnvironment = require('../utils/test_environment_preparer');  

const path = '/v1/admin/recipes'; 

test(`API GET ${path}`, co.wrap(function* (t) { 
 yield testEnvironment.prepare();
 const recipe1 = yield factory.create('recipe'); 
 const recipe2 = yield factory.create('recipe'); 

 const serverResponse = yield superTest.get(path); 

 t.deepEqual(serverResponse.body, [recipe1, recipe2]); 
}));
The code above is testing an API (GET /v1/admin/recipes) that expects it to return an array of saved recipes as a response.
You can see that the test, as simple as it may be, relies on a lot of utilities. This is common for any good integration test suite.
Helper components make it easy to write comprehensible integration tests.
Let’s review what components are needed for integration testing.

Helper Components

A comprehensive testing suite has a few basic ingredients, including: flow control, testing framework, database handler, and a way to connect to backend APIs.

Flow Control

One of the biggest challenges in JavaScript testing is the asynchronous flow.
Callbacks can wreak havoc in code and promises are just not enough. This is where flow helpers become useful.
While waiting for async/await to be fully supported, libraries with similar behavior can be used. The goal is to write readable, expressive, and robust code with the possibility of having async flow.
Co enables code to be written in a nice way while it keeps it non-blocking. This is done through defining a co generator function and then yielding results.
Another solution is to use Bluebird. Bluebird is a promise library that has very useful features like handling of arrays, errors, time, etc.
Co and Bluebird coroutine behave similarly to async/await in ES7 (waiting for resolution before continuing), the only difference being that it will always return a promise, which is useful for handling errors.

Testing Framework

Choosing a test framework just comes down to personal preference. My preference is a framework that is easy to use, has no side effects, and which output is easily readable and piped.
There’s a wide array of testing frameworks in JavaScript. In our examples, we are using Tape. Tape, in my opinion, not only fulfills these requirements, but also is cleaner and simpler than other test frameworks like Mocha or Jasmin.
Tape is based on the Test Anything Protocol (TAP).
TAP has variations for most programming languages.
Tape takes tests as an input, runs them, and then outputs results as a TAP. The TAP result can then be piped to the test reporter or can be output to the console in a raw format. Tape is run from the command line.
Tape has some nice features, like defining a module to load before running the entire test suite, providing a small and simple assertion library, and defining the number of assertions that should be called in a test. Using a module to preload can simplify preparing a test environment, and remove any unnecessary code.

Factory Library

A factory library allows you to replace your static fixture files with a much more flexible way to generate data for a test. Such a library allows you to define models and create entities for those models without writing messy, complex code.
JavaScript has factory_girl for this - a library inspired from a gem with a similar name, which was originally developed for Ruby on Rails.
const factory = require('factory-girl').factory; 
const User = require('../models/user'); 

factory.define('user', User, { username: 'Bob', number_of_recipes: 50 }); 

const user = factory.build('user');
To start, a new model must be defined in factory_girl.
It’s specified with a name, a model from your project, and an object from which a new instance is generated.
Alternatively, instead of defining the object from which a new instance is generated, a function can be provided that will return an object or a promise.
When creating a new instance of a model, we can:
  • Override any value in the newly generated instance
  • Pass additional values to the build function option
Let’s see an example.
const factory = require('factory-girl').factory; 
const User = require('../models/user'); 

factory.define('user', User, (buildOptions) => {
 return {
  name: 'Mike',
  surname: 'Dow',
  email: buildOptions.email ||  'mike@gmail.com'
 }
}); 

const user1 = factory.build('user');
// {"name": "Mike", "surname": "Dow", "email": "mike@gmail.com"}

const user2 = factory.build('user', {name: 'John'}, {email: 'john@gmail.com'});
// {"name": "John", "surname": "Dow", "email": "john@gmail.com"}

Connecting to APIs

Starting a full-blown HTTP server and making an actual HTTP request, only to tear it down a few seconds later – especially when conducting multiple tests – is totally inefficient and may cause integration tests to take significantly longer than necessary.
SuperTest is a JavaScript library for calling APIs without creating a new active server. It’s based on SuperAgent, a library for creating TCP requests. With this library, there is no need to create new TCP connections. APIs are almost instantly called.
SuperTest, with support for promises, is supertest-as-promised. When such a request returns a promise, it lets you avoid multiple nested callback functions, making it far easier to handle the flow.
const express = require('express') 
const request = require('supertest-as-promised'); 

const app = express(); 
request(app).get("/recipes").then(res => assert(....)); 
SuperTest was made for the Express.js framework, but with small changes it can be used with other frameworks as well.

Other Utilities

In some cases, there’s a need to mock some dependency in our code, test logic around functions using spies, or use stubs at certain places. This is where some of these utility packages come in handy.
SinonJS is a great library that supports spies, stubs, and mocks for tests. It also supports other useful testing features, like bending time, test sandbox, and expanded assertion, as well as fake servers and requests.
In some cases, there is a need to mock some dependency in our code. References to services that we would like to mock are used by other parts of the system.
To resolve this problem, we can use dependency injection or, if that is not an option, we can use a mocking service like Mockery.
Mockery helps mocking code that has external dependencies. To use it properly, Mockery should be called before loading tests or code.
const mockery = require('mockery'); 
mockery.enable({ 
warnOnReplace: false, 
warnOnUnregistered: false 
}); 

const mockingStripe = require('lib/services/internal/stripe'); mockery.registerMock('lib/services/internal/stripe', mockingStripe);
With this new reference (in this example, mockingStripe), it is easier to mock services later in our tests.
const stubStripeTransfer = sinon.stub(mockingStripe, 'transferAmount');
stubStripeTransfer.returns(Promise.resolve(null));
With the help of Sinon library, it is easy to mock. The only problem here is that this stub will propagate to other tests. To sandbox it, the sinon sandbox can be used. With it, later tests can bring the system back to its initial state.
const sandbox = require('sinon').sandbox.create();
const stubStripeTransfer = sandbox.sinon.stub(mockingStripe, 'transferAmount');
stubStripeTransfer.returns(Promise.resolve(null));

// after the test, or better when starting a new test

sandbox.restore();
There is a need for other components for functions like:
  • Emptying the database (can be done with one hierarchy pre-build query)
  • Setting it to working state (sequelize-fixtures)
  • Mocking TCP requests to 3rd party services (nock)
  • Using richer assertions (chai)
  • Saved responses from third-parties (easy-fix)

Not-so-simple Tests

Abstraction and extensibility are key elements to building an effective integration test suite. Everything that removes focus from the core of the test (preparation of its data, action and assertion) should be grouped and abstracted into utility functions.
Although there is no right or wrong path here, as everything depends on the project and its needs, some key qualities are still common to any good integration test suite.
The following code shows how to test an API that creates a recipe and sends an email as a side-effect.
It stubs the external email provider so that you can test if an email would have been sent without actually sending one. The test also verifies if the API responded with the appropriate status code.
const co = require('co'); 
const factory = require('factory');
const superTest = require('../utils/super_test');  
const basicEnv = require('../utils/basic_test_enivornment'); 

const path = '/v1/admin/recipes'; 

basicEnv.test(`API POST ${path}`, co.wrap(function* (t, assert, sandbox) { 
 const chef = yield factory.create(‘chef’); 
 const body = {
  chef_id: chef.id,
  recipe_name: ‘cake’,
  Ingredients: [‘carrot’, ‘chocolate’, ‘biscuit’]
 }; 
 
 const stub = sandbox.stub(mockery.emailProvider, 'sendNewEmail').returnsPromise(null);
 const serverResponse = yield superTest.get(path, body); 
 
 assert.spies(stub).called(1);
 assert.statusCode(serverResponse, 201);
}));
The test above is repeatable as it starts with a clean environment every time.
It has a simple setup process, where everything related to the setup is consolidated inside the basicEnv.test function.
It tests only one action - a single API. And it clearly states the test’s expectations through simple assert statements. Also, the test doesn’t involve third-party code by stubbing/mocking.

Start Writing Integration Tests

When pushing new code to production, developers (and all other project participants) want to be sure that new features will work and old ones won’t break.
This is very hard to achieve without testing, and if done poorly can lead to frustration, project fatigue, and eventually project failure.
Integration tests, combined with unit tests, are the first line of defense.
Using only one of the two is insufficient and will leave a lot of space for uncovered errors. Always utilizing both will make new commits robust, and deliver confidence and inspire trust in all project participants.
Article via Toptal

Thursday, December 15, 2016

What is Bootstrap? A Short Bootstrap Tutorial on the What, Why, and How

If you’re doing anything web related, chances are you’ve heard about Bootstrap. If by now you still don’t know what Bootstrap is, or you just want to find a bootstrap tutorial for beginners to get a better overview of what it is and what it does best, you’ve come to the right place.
Bootstrap is a powerful toolkit - a collection of HTML, CSS, and JavaScript tools for creating and building web pages and web applications. It is a free and open source project, hosted on GitHub, and originally created by (and for) Twitter.
Toptal's bootstrap tutorial
After its open source release in 2011, Bootstrap became popular very quickly, and not without reason. Web designers and web developers like Bootstrap because it is flexible and easy to work with. Its main advantages are that it is responsive by design, it maintains wide browser compatibility, it offers consistent design by using re-usable components, and it is very easy to use and quick to learn. It offers rich extensibility using JavaScript, coming with built-in support for jQuery plugins and a programmatic JavaScript API. Bootstrap can be used with any IDE or editor, and any server side technology and language, from ASP.NET to PHP to Ruby on Rails.
With Bootstrap, web developers can concentrate on the development work, without worrying about design, and get a good looking website up and running quickly. Conversely, it gives web designers a solid foundation for creating interesting Bootstrap themes.

Getting Started with this Bootstrap Tutorial

Bootstrap is available in two forms; as a precompiled version, and as a source code version. The source code version uses the Less CSS preprocessor, but if you are more into Sass, there is an official Sass port of Bootstrap also available. To make it easier to make use of CSS vendor prefixes, Bootstrap uses Autoprefixer.
The source code version comes styles source code written in Less (or Sass), all the JavaScript, and accompanying documentation. This allows more ambitious designers and developers to change and customize, at their will, all the provided styles, and to build their own version of Bootstrap. But if you are not familiar with Less (or Sass), or you are just not interested in changing the source code, don’t worry. You can just use the precompiled vanilla CSS. All the styles can be overridden later by using custom styles.

File Structure

We’ll focus on the precompiled version, which can be downloaded here. When you download the zip archive and uncompress it, the basic file structure looks like this:
bootstrap/
├── css/
│   ├── bootstrap.css
│   ├── bootstrap.css.map
│   ├── bootstrap.min.css
│   ├── bootstrap-theme.css
│   ├── bootstrap-theme.css.map
│   └── bootstrap-theme.min.css
├── js/
│   ├── bootstrap.js
│   └── bootstrap.min.js
└── fonts/
    ├── glyphicons-halflings-regular.eot
    ├── glyphicons-halflings-regular.svg
    ├── glyphicons-halflings-regular.ttf
    ├── glyphicons-halflings-regular.woff
    └── glyphicons-halflings-regular.woff2
The Bootstrap structure is pretty simple and self-explanatory. It includes precompiled files that enable quick usage in any web project. Besides compiled and minified CSS and JS files, it also includes fonts from Glyphicons, and the optional starting Bootstrap theme.
This structure can be easily incorporated in your own project’s file structure by just including the Bootstrap files exactly as they come out of the zip archive, or if it suits your project better, you can rearrange these files and place them anywhere you like. Just be sure that the Glyphicons fonts folder is on the same level as the CSS folder.

Basic HTML Template

A basic Bootstrap HTML template should look something like this:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap Template</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body>
    <h1>Hello, world!</h1>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
  </body>
</html>
It is important to start any HTML with a HTML 5 Doctype declaration, so that browsers know what kind of a document they can expect. The head contains three important <meta> tags that must be declared first, and any additional head tags must be added after these. If you want to support older browsers like IE8, you can also include HTML 5 shim in the head, which will enable use of HTML5 elements in older browsers, and Respond.js, that will polyfill CSS3 Media Queries, in the old versions of Internet Explorer.
<head>
  ...
  <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
  <![endif]-->
</head>
Although this is not very important if you are targeting only modern browsers.
JavaScript files are added to the end of the body to allow the web page to load visibly before any JavaScript is executed. jQuery is needed for Bootstrap plugins, and needs to load before bootstrap.js. If you aren’t using any of Bootstrap’s interactive features, you can also omit these files from the source.
This is the bare minimum that is needed to get a basic Bootstrap layout up and running. If you’re a developer, you’ll probably want to take a look at some more advanced examples at Bootstrap’s examples page. If you’re a designer, or just looking for inspiration, Bootstrap Expo showcases sites that are built using Bootstrap. As we’ll see later, every part of Bootstrap can be easily customized in CSS. But if that’s not your thing, and you are looking for a slightly different look and feel from the prepackaged Bootstrap themes, there are a lot of free, open source and premium themes available from sources like Bootswatch and WrapBootstrap.

Components

Bootstrap comes bundled with basic HTML and CSS design templates that include many common UI components. These include Typography, Tables, Forms, Buttons, Glyphicons, Dropdowns, Buttons and Input Groups, Navigation, Pagination, Labels and Badges, Alerts, Progress Bars, Modals, Tabs, Accordions, Carousels, and many others. Many of these use JavaScript extensions and jQuery plugins.
These templates are made available as well-factored CSS classes that you can apply to your HTML to achieve different effects. This makes using Bootstrap very convenient. By using semantic class names like .success.warning and .info, these components are easily reusable and extensible. But while Bootstrap uses descriptive class names that have meaning, it isn’t specific about implementation details. All classes can be overridden with custom CSS style and color, and still the meaning of the class will stay the same.

Grids

Before we dive more into Bootstrap components and design templates, it is important to mention one of the major features that Bootstrap introduced in version 3: a mobile-first design philosophy, which resulted in a Bootstrap that is responsive by design. The end result is that Bootstrap easily and efficiently scales with a single code base, from phones, through tablets, to desktops.
This responsiveness is achieved using a fluid grid system that can be applied to appropriately scale up to 12 columns according to the size of the device or viewport. Grids provide structure to the layout, defining the horizontal and vertical guidelines for arranging content and enforcing margins. Grids also offer an intuitive structure for viewers, because it’s easy to follow a left to right, or a right to left flow of content moving down the page. Before grids, and before CSS was so powerful, grid based layouts were achieved by using tables, where the content would be arranged inside table cells. As CSS became more mature, a number of CSS frameworks for grid-based layouts started to appear. These include YUI grids960 GS and blueprint, to name a few.
To use the Bootstrap grid system, a few rules need to be followed. Grid column elements are placed inside row elements, which create horizontal groups of columns. You can have as many rows as you want on the page, but columns must be immediate children of rows. In a full row, the column widths will be any combination that adds up to 12, but it is not mandatory to use all 12 available columns.
Rows need to be placed either in a fixed-width layout wrapper, which has a .container class and a width of 1170px, or in full-width layout wrapper, which has a .container-fluid class, and which enables the responsive behavior in that row.
The Bootstrap grid system has four tiers of classes: xs for phones (<768px), sm for tablets (≥768px), md for desktops (≥992px), and lg for larger desktops (≥1200px). These basically define the sizes at which the columns will collapse or spread horizontally. The class tiers can be used in any combination to get dynamic and flexible layouts.
For example, if we want to get two rows, one with two columns, and one with four, we could write:
<div class="row">
  <div class="col-md-6">First column</div>
  <div class="col-md-6">Second column</div>
</div>
<div class="row">
  <div class="col-md-3">First column</div>
  <div class="col-md-3">Second column</div>
  <div class="col-md-3">Third column</div>
  <div class="col-md-3">Fourth column</div>
</div>
We can use mixed column widths, too:
<div class="row">
  <div class="col-md-9">Wider column</div>
  <div class="col-md-3">Smaller column</div>
</div>
We can even shift columns by using offset, for example to create more narrow and centered content:
<div class="row">
  <div class="col-md-6 col-md-offset-3">Centered column</div>
</div>
Columns can be nested. There can be fewer than 12 columns, and as mentioned above, we can choose fixed-width or full-width columns by using .container or .container-fluid wrappers, respectively.
<div class="container">
  <div class="row">
    <div class="col-md-8">
      Parent fixed-width column
      <div class="row">
        <div class="col-md-6">Nested column</div>
        <div class="col-md-6">Nested column</div>
      </div>
    </div>
  </div>
</div>
<div class="container-fluid">
  <div class="row">
    <div class="col-md-4">Fluid ..</div>
    <div class="col-md-4">.. and full-width ..</div>
    <div class="col-md-4">.. example</div>
  </div>
</div>
If we combine different class tiers, we will get different looks on mobile and on desktop views. In the example below, on the desktop there will be 4 columns in a line, and on mobile they will have full width and stack on each other.
<div class="row">
  <div class="col-xs-12 col-md-3">.col-xs-12 .col-md-3</div>
  <div class="col-xs-12 col-md-3">.col-xs-12 .col-md-3</div>
  <div class="col-xs-12 col-md-3">.col-xs-12 .col-md-3</div>
  <div class="col-xs-12 col-md-3">.col-xs-12 .col-md-3</div>
</div>
Bootstrap on desktop and mobile
It is possible to disable page responsiveness completely. This will basically disable the “mobile site” aspects of Bootstrap. Just keep in mind that if you disable responsiveness, any fixed-width component, such as a fixed navbar, will not be visible when the viewport becomes narrower than the page content. For a non-responsive container, that means a width of 970px. Also in this case, navbars won’t collapse in mobile views as described later.
These are just basic examples. To see the full potential of the grids, check out Bootstrap’s Grids documentation.

Typography

Beginning developers often assume their pure and un-styled HTML will look the same across all browsers. Unfortunately, every browser has its own default “user agent” style sheet that is applied to the HTML, and no two browsers have the same defaults. For example, heading font sizes are not consistent across browsers, some unordered and ordered lists have left margins and others have left padding, browsers apply custom borders and padding to the HTML body, and even buttons are rendered differently across browsers. To solve all these inconsistencies, different CSS “reset” rules were born that define consistent style defaults.
Bootstrap brings some more goodies to table besides pure CSS reset. It comes with normalize.css, an HTML5-ready alternative to CSS resets, and it also has some well-designed defaults of its own. For example, Bootstrap sets the global default font-size to 14px, with a line-height of 1.428. The default font is changed to Helvetica/Arial, with sans serif fallback. All these styles are applied to the <body> and all paragraphs, with the addition that <p> (paragraphs) receive a bottom margin of half their computed line-height (10px by default). Besides these defaults, there are also customizable styles for standard HTML tags that bring more consistency to the text, such as highlighted text (<mark>), deleted text (<del> and <s>), underlined text (<u>), small text (<small>), and bold text (<strong>). Alignment classes help to arrange content on the page more easily by using .text-left.text-center.text-right.text-justify and .text-nowrap classes. There are also predefined styles for block quotes, and unordered and ordered list, with inline options, just to name a few. To get a full list, head to the Bootstrap Typography page.
One interesting thing that Bootstrap also makes possible is that you can use, for example, heading styles by using either the <h1> tag, or the .h1 class. The latter will match the styling of the <h1> heading, but will allow the text to be displayed inline.
bootstrap styling

Forms

Forms have come a long way over the years, and today using a web form is one of the most common activities performed while browsing the web. While HTML5 introduced a number of new form attributes, input types, and other helper elements, browsers haven’t visually improved forms much. This is one area where Bootstrap really shines, because aligning and styling labels and inputs, validating forms, and showing error messages, can be tricky without some help.
First, Bootstrap sets all textual input elements, like <input><textarea>, and <select>, to 100% width of the parent form element. It also gives you the ability to choose between inline forms, which will render multiple labels and input fields in the same line, by using the .form-inline class, or horizontal forms, which use grids to align each input in its own row, by using the .form-horizontal class. And if you need to place plain text next to a form label, instead of the input field, you can give it the .form-control-static class to make it match the visual look of the form.
Maybe the greatest feature that Bootstrap brings to forms is validation styles for error, warning, and success states. These can be applied using the .has-warning.has-error, and .has-success classes, respectively. Combining this with icons that can be placed inside the input forms, we can get quick and effective form validation effects, even without using any error text message.
The follow code snippet will generate an input field with an @ sign, to indicate that we are looking for an email, and with a warning icon and a yellow outline that indicates that there is something wrong in the input field.
<div class="form-group has-warning has-feedback">
  <label class="control-label" for="inputWarning">Email address input field with warning</label>
  <div class="input-group">
    <span class="input-group-addon">@</span>
    <input type="text" class="form-control" id="inputWarning" aria-describedby="inputGroupWarningStatus">
  </div>
  <span class="glyphicon glyphicon-warning-sign form-control-feedback" aria-hidden="true"></span>
  <span id="inputGroupWarningStatus" class="sr-only">(warning)</span>
</div>
Bootstrap input field
Again, we have only scratched the surface here. For more examples, take a look at Bootstrap’s Forms documentation.

Images and Icons

Images in Bootstrap can be made responsive by simply giving them the .img-responsive class. This will apply max-width:100%; height:auto; and display:block; to the image in question, so that it scales to the parent element.
Besides making images responsive, we can easily add different effects. For example, rounded corners are applied with the .img-rounded class, and the image can be shaped to be a circle by using .img-circle, or to a thumbnail by using .img-thumbnail class.
Bootstrap comes bundled with over 260 glyphs in font format, from the Glyphicons Halflings set. Jan Kovařík, author and designer of Glyphicons, has made them available for Bootstrap for free and under the same license as Bootstrap, which is awesome. Font icons have many advantages over plain raster images, a big one being that they are scalable. They can also easily be customized using just CSS, so manipulating size or color, or even adding a drop a shadow, is a breeze.

Buttons, Button Groups, and Button Dropdowns

Buttons are one of the things every browser renders totally differently. If you want to have consistent design across all browsers, this is potentially a big problem. Luckily, Bootstrap has an elegant solution for buttonsalso. And besides making them consistent, it brings a lot of variations to play with. You can apply the .btnclass to <a> and <input> elements. You can group a series of buttons together into a single line using the .btn-group class on the parent <div>. With a little help from JavaScript, you can create radio- and checkbox- style behavior on buttons. Or you can turn your buttons into dropdown menus by placing it within a .btn-group, and providing the proper menu markup of unordered list of items.
The navigational bar, or navbar, is a Bootstrap component designed specifically to build the primary navigation menu of the website. On big screens, it is displayed horizontally, and on small and mobile screens (those below 768px), it transformed into a “hamburger” dropdown menu. Under the hood, navbar is an unordered inline list of menu items, with additional HTML elements that are added as desired. Among the possible additions are branding (either text or logo), form items such as a search bar, and menu dropdowns. Two styles are available to choose from out-of-the-box: light and dark, inverted. Items in the navbar can be aligned left or right by applying .navbar-left or .navbar-right classes, respectively.
Navbars can have 4 different position behaviors. The default float position has buffer space around it; the full-width static navbar scrolls away when the user scrolls down the page, and the fixed navbar, which can be either on the top or the bottom of the window, is always visible on the page, no matter where the user has scrolled to.
Bootstrap navbars

Conclusion

This covers only a few of the great Bootstrap components that puts Bootstrap ahead of similar frameworks, libraries, and toolkits. With Bootstrap, just a few simple CSS classes are all it takes to build a fully responsive and beautiful front end, fast and easily. It’s a great starting point for your next big project or startup.
This article was originally posted on Toptal