Access your localhost in any device

ngrok really rocks..


satvakac$ cd /Users/satvakac/Downloads/ngrok

ngrok satvakac$ unzip
inflating: ngrok

ngrok satvakac$ mv ngrok /usr/local/bin
ngrok satvakac$ ngrok

ngrok satvakac$ ngrok -v
ngrok version 2.2.8

ngrok satvakac$ ngrok authtoken 6VgvCTLNXgin9ZzcM5Az_3e7ytpBgQADi3tcFojLYY
Authtoken saved to configuration file: /Users/satvakac/.ngrok2/ngrok.yml

ngrok satvakac$ ngrok http 3000



Common Matchers

The simplest way to test a value is with exact equality.

test('two plus two is four', () => {
  expect(2 + 2).toBe(4);

In this code, expect(2 + 2) returns an “expectation” object. You typically won’t do much with these expectation objects except call matchers on them. In this code, .toBe(4) is the matcher.

toBe uses to test exact equality. If you want to check the value of an object, use toEqual instead:

test('object assignment', () => {
  const data = {one: 1};
  data['two'] = 2;
  expect(data).toEqual({one: 1, two: 2});

toEqual recursively checks every field of an object or array.


In tests you sometimes need to distinguish between undefined, null, and false, but you sometimes do not want to treat these differently. Jest contains helpers that let you be explicit about what you want.

  • toBeNull matches only null
  • toBeUndefined matches only undefined
  • toBeDefined is the opposite of toBeUndefined
  • toBeTruthy matches anything that an if statement treats as true
  • toBeFalsy matches anything that an if statement treats as false

For example:

test('null', () => {
  const n = null;

test('zero', () => {
  const z = 0;

You should use the matcher that most precisely corresponds to what you want your code to be doing.


Most ways of comparing numbers have matcher equivalents.

test('two plus two', () => {
  const value = 2 + 2;

  // toBe and toEqual are equivalent for numbers

For floating point equality, use toBeCloseTo instead of toEqual, because you don’t want a test to depend on a tiny rounding error.

test('adding floating point numbers', () => {
  const value = 0.1 + 0.2;
  //expect(value).toBe(0.3);           This won't work because of rounding error
  expect(value).toBeCloseTo(0.3); // This works.


You can check strings against regular expressions with toMatch:

test('there is no I in team', () => {

test('but there is a "stop" in Christoph', () => {


You can check if an array contains a particular item using toContain:

const shoppingList = [
  'trash bags',
  'paper towels',

test('the shopping list has beer on it', () => {


If you want to test that a particular function throws an error when it’s called, use toThrow.

function compileAndroidCode() {
  throw new ConfigError('you are using the wrong JDK');

test('compiling android goes as expected', () => {

  // You can also use the exact error message or a regexp
  expect(compileAndroidCode).toThrow('you are using the wrong JDK');

Testing Asynchronous Code

It’s common in JavaScript for code to run asynchronously. When you have code that runs asynchronously, Jest needs to know when the code it is testing has completed, before it can move on to another test. Jest has several ways to handle this.


The most common asynchronous pattern is callbacks.

For example, let’s say that you have a fetchData(callback) function that fetches some data and calls callback(data) when it is complete. You want to test that this returned data is just the string 'peanut butter'.

By default, Jest tests complete once they reach the end of their execution. That means this test will not work as intended:

// Don't do this!
test('the data is peanut butter', () => {
  function callback(data) {
    expect(data).toBe('peanut butter');


The problem is that the test will complete as soon as fetchData completes, before ever calling the callback.

There is an alternate form of test that fixes this. Instead of putting the test in a function with an empty argument, use a single argument called done. Jest will wait until the done callback is called before finishing the test.

test('the data is peanut butter', done => {
  function callback(data) {
    expect(data).toBe('peanut butter');


If done() is never called, the test will fail, which is what you want to happen.


If your code uses promises, there is a simpler way to handle asynchronous tests. Just return a promise from your test, and Jest will wait for that promise to resolve. If the promise is rejected, the test will automatically fail.

For example, let’s say that fetchData, instead of using a callback, returns a promise that is supposed to resolve to the string 'peanut butter'. We could test it with:

test('the data is peanut butter', () => {
  return fetchData().then(data => {
    expect(data).toBe('peanut butter');

Be sure to return the promise – if you omit this return statement, your test will complete before fetchData completes.

If you expect a promise to be rejected use the .catch method. Make sure to add expect.assertions to verify that a certain number of assertions are called. Otherwise a fulfilled promise would not fail the test.

test('the fetch fails with an error', () => {
  return fetchData().catch(e => expect(e).toMatch('error'));

.resolves / .rejects

You can also use the .resolves matcher in your expect statement, and Jest will wait for that promise to resolve. If the promise is rejected, the test will automatically fail.

test('the data is peanut butter', () => {
  return expect(fetchData()).resolves.toBe('peanut butter');

Be sure to return the assertion—if you omit this return statement, your test will complete before fetchData completes.

If you expect a promise to be rejected use the .rejects matcher. It works analogically to the .resolves matcher. If the promise is fulfilled, the test will automatically fail.

test('the fetch fails with an error', () => {
  return expect(fetchData()).rejects.toMatch('error');


Alternatively, you can use async and await in your tests. To write an async test, just use the async keyword in front of the function passed to test. For example, the same fetchData scenario can be tested with:

test('the data is peanut butter', async () => {
  const data = await fetchData();
  expect(data).toBe('peanut butter');

test('the fetch fails with an error', async () => {
  try {
    await fetchData();
  } catch (e) {

Setup and Teardown

Often while writing tests you have some setup work that needs to happen before tests run, and you have some finishing work that needs to happen after tests run. Jest provides helper functions to handle this.

Repeating Setup For Many Tests

If you have some work you need to do repeatedly for many tests, you can use beforeEach and afterEach.

For example, let’s say that several tests interact with a database of cities. You have a method initializeCityDatabase() that must be called before each of these tests, and a method clearCityDatabase() that must be called after each of these tests. You can do this with:

beforeEach(() => {

afterEach(() => {

test('city database has Vienna', () => {

test('city database has San Juan', () => {
  expect(isCity('San Juan')).toBeTruthy();

beforeEach and afterEach can handle asynchronous code in the same ways that tests can handle asynchronous code – they can either take a done parameter or return a promise. For example, if initializeCityDatabase() returned a promise that resolved when the database was initialized, we would want to return that promise

beforeEach(() => {
  return initializeCityDatabase();

One-Time Setup

In some cases, you only need to do setup once, at the beginning of a file. This can be especially bothersome when the setup is asynchronous, so you can’t just do it inline. Jest provides beforeAll and afterAll to handle this situation.

For example, if both initializeCityDatabase and clearCityDatabase returned promises, and the city database could be reused between tests, we could change our test code to:

beforeAll(() => {
  return initializeCityDatabase();

afterAll(() => {
  return clearCityDatabase();

test('city database has Vienna', () => {

test('city database has San Juan', () => {
  expect(isCity('San Juan')).toBeTruthy();


By default, the before and after blocks apply to every test in a file. You can also group tests together using a describe block. When they are inside a describe block, the before and after blocks only apply to the tests within that describe block.

For example, let’s say we had not just a city database, but also a food database. We could do different setup for different tests:

// Applies to all tests in this file
beforeEach(() => {
  return initializeCityDatabase();
test('city database has Vienna', () => {
describe('matching cities to foods', () => {
  // Applies only to tests in this describe block
  beforeEach(() => {
    return initializeFoodDatabase();

  test('Vienna <3 sausage', () => {
    expect(isValidCityFoodPair('Vienna', 'Wiener Schnitzel')).toBe(true);

Order of execution of describe and test blocks

Jest executes all describe handlers in a test file before it executes any of the actual tests. This is another reason to do setup and teardown in before* and after* handlers rather in the describe blocks. Once the describe blocks are complete, by default Jest runs all the tests serially in the order they were encountered in the collection phase, waiting for each to finish and be tidied up before moving on.

Consider the following illustrative test file and output:

describe('outer', () => {
  console.log('describe outer-a');

  describe('describe inner 1', () => {
    console.log('describe inner 1');
    test('test 1', () => {
      console.log('test for describe inner 1');

  console.log('describe outer-b');

  test('test 1', () => {
    console.log('test for describe outer');

  describe('describe inner 2', () => {
    console.log('describe inner 2');
    test('test for describe inner 2', () => {
      console.log('test for describe inner 2');

  console.log('describe outer-c');

// describe outer-a
// describe inner 1
// describe outer-b
// describe inner 2
// describe outer-c
// test for describe inner 1
// test for describe outer
// test for describe inner 2

General Advice

If a test is failing, one of the first things to check should be whether the test is failing when it’s the only test that runs. In Jest it’s simple to run only one test – just temporarily change that test command to a test.only:

test.only('this will be the only test that runs', () => {

test('this test will not run', () => {

If you have a test that often fails when it’s run as part of a larger suite, but doesn’t fail when you run it alone, it’s a good bet that something from a different test is interfering with this one. You can often fix this by clearing some shared state with beforeEach. If you’re not sure whether some shared state is being modified, you can also try a beforeEach that just logs data.

Mock Functions

Mock functions make it easy to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with new, and allowing test-time configuration of return values.

There are two ways to mock functions: Either by creating a mock function to use in test code, or writing a manual mock to override a module dependency.

Mock Return Values

Mock functions can also be used to inject test values into your code during a test:

const myMock = jest.fn();
// > undefined


console.log(myMock(), myMock(), myMock(), myMock());
// > 10, 'x', true, true

Snapshot Testing

Snapshot tests are a very useful tool whenever you want to make sure your UI does not change unexpectedly.

A typical snapshot test case for a mobile app renders a UI component, takes a screenshot, then compares it to a reference image stored alongside the test. The test will fail if the two images do not match: either the change is unexpected, or the screenshot needs to be updated to the new version of the UI component.

Snapshot Testing with Jest

A similar approach can be taken when it comes to testing your React components. Instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree. Consider this example test for a simple Link component:

import React from 'react';
import Link from '../Link.react';
import renderer from 'react-test-renderer';

it('renders correctly', () => {
  const tree = renderer
    .create(<Link page="">Facebook</Link>)

The first time this test is run, Jest creates a snapshot file that looks like this:

exports[`renders correctly 1`] = `

On subsequent test runs Jest will simply compare the rendered output with the previous snapshot. If they match, the test will pass. If they don’t match, either the test runner found a bug in your code (in this case, it’s <Link> component) that should be fixed, or the implementation has changed and the snapshot needs to be updated.

Update Snapshot using -u


Understanding React

Some basics of react in simple words:

what are props?

props – props are like html attributes and pass this to any component. so, component will have access to props.

what is state?

state is an object that lives with the component and responsible for keeping track of changing data within component. that change could be result of user interaction like click etc.

In other words, state is an object that lives inside a component and holds the data for self need or for its children.

When DOM Re-render?

Only when internal state or external props get changed, then component will re-render

what is ref?

ref allows us to react to reference an actual dom node on the page.

stateless component

stateless arrow function syntax can be used instead of regular class XYZ extends React.Component.

const Header = (props) => ();

For more check this article.

React Context

Explained clearly on official documention:


The result of getDefaultProps() will be cached and used to ensure that this.props.value will have a value if it was not specified by the parent component.


Triggered before render().


Called after render. Can access refs. The componentDidMount() method of child components is invoked before that of parent components. This is the place to call external libraries, use setTimeout, make ajax requests

shouldComponentUpdate(nextProps, nextState) – Update only

called when there are new props or state changes. return false to prevent a render. good for performance.

componentWillReceiveProps(nextProps) – Update only

Called before render when props change. Access to old props. It is not triggered after the component is mounted.

componentWillUpdate(nextProps, nextState)

Invoked immediately before rendering when new props or state are being received. Not called for the initial render. Cannot use setState in this method. Use componentWillReceiveProps instead. Use this as an opportunity to perform preparation before an update occurs.


Triggered when the state changes.

componentDidUpdate(prevState, prevProps) – Update only

Access to prevState, prevProps Use this as an opportunity to operate on the DOM when the component has been updated.


Clean up event bindings, etc.

React CheatSheet

Controlled Form Inputs

Form is stateful and this is only stateful part of UI. Inputs are not stateful and display the data that are provided with. One we edit text, we will dispatch change event via onChange call back and our form handles and stores in state. Then it passes the new value to input component. This entire pattern is known as controlled form inputs

Use of Render Method in React?

Each time the component render/re-render, it has to execute all the statements in it. To make sure view is in sync.

VS Code Extensions

These are the best extensions that i configured to enable best features and rich UX as shown below..

Some of the VS Code features here..

Rename All Occurrences

Refactoring is a necessary aspect of writing and maintaining clean code, but it can be quite the headache — especially when you’re refactoring a large module or an otherwise huge chunk of code. So instead of hunting through dozens of files just to rename a variable or method, let VS Code do it for you.

If you select a variable/method and hit F2, you can edit the name and it will change every instance of that variable’s name throughout the entire current working project.

If you only want to change within the current file, use the Command + F2 (on Mac) or Ctrl + F2 (on Windows) keyboard shortcut and VS Code will spawn a cursor at every instance throughout the current file.

Go to Definition

When you’re programming or scripting, often times you’ll run into a variable or method that you don’t recognize. So what do you do? You could spend several minutes searching for the right file, or you could press Command (on Mac) or Ctrl (on Windows) key and click the variable/method with your mouse. VS Code will take you to it’s definition right away.

Or you could just hover your cursor over the variable/method along with pressing the Command (on Mac) or Ctrl (on Windows) key, it will shows you the definition right in line where your cursor is.

Edit Multiple Lines at Once

If you ever need to insert or delete multiple instances of text throughout a document, all you have to do is create multiple cursors. You can do this by holding down Option (on Mac) or Alt (on Windows) and clicking anywhere in the text. Every click creates a new cursor.

This is particularly useful for things like HTML, where you might want to add many instances of the same class or change the format of several hyperlinks.

Few More here