Access your localhost in any device

ngrok really rocks..

https://ngrok.com/download

Steps:

satvakac$ cd /Users/satvakac/Downloads/ngrok

ngrok satvakac$ unzip ngrok-stable-darwin-amd64.zip
Archive: ngrok-stable-darwin-amd64.zip
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

Advertisements

JEST BASICS

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 Object.is 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.

Truthiness

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;
  expect(n).toBeNull();
  expect(n).toBeDefined();
  expect(n).not.toBeUndefined();
  expect(n).not.toBeTruthy();
  expect(n).toBeFalsy();
});

test('zero', () => {
  const z = 0;
  expect(z).not.toBeNull();
  expect(z).toBeDefined();
  expect(z).not.toBeUndefined();
  expect(z).not.toBeTruthy();
  expect(z).toBeFalsy();
});

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

Numbers

Most ways of comparing numbers have matcher equivalents.

test('two plus two', () => {
  const value = 2 + 2;
  expect(value).toBeGreaterThan(3);
  expect(value).toBeGreaterThanOrEqual(3.5);
  expect(value).toBeLessThan(5);
  expect(value).toBeLessThanOrEqual(4.5);

  // toBe and toEqual are equivalent for numbers
  expect(value).toBe(4);
  expect(value).toEqual(4);
});

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.
});

Strings

You can check strings against regular expressions with toMatch:

test('there is no I in team', () => {
  expect('team').not.toMatch(/I/);
});

test('but there is a "stop" in Christoph', () => {
  expect('Christoph').toMatch(/stop/);
});

Arrays

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

const shoppingList = [
  'diapers',
  'kleenex',
  'trash bags',
  'paper towels',
  'beer',
];

test('the shopping list has beer on it', () => {
  expect(shoppingList).toContain('beer');
});

Exceptions

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', () => {
  expect(compileAndroidCode).toThrow();
  expect(compileAndroidCode).toThrow(ConfigError);

  // You can also use the exact error message or a regexp
  expect(compileAndroidCode).toThrow('you are using the wrong JDK');
  expect(compileAndroidCode).toThrow(/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.

Callbacks

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');
  }

  fetchData(callback);
});

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');
    done();
  }

  fetchData(callback);
});

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

Promises

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', () => {
  expect.assertions(1);
  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', () => {
  expect.assertions(1);
  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', () => {
  expect.assertions(1);
  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', () => {
  expect.assertions(1);
  return expect(fetchData()).rejects.toMatch('error');
});

Async/Await

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 () => {
  expect.assertions(1);
  const data = await fetchData();
  expect(data).toBe('peanut butter');
});

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

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(() => {
  initializeCityDatabase();
});

afterEach(() => {
  clearCityDatabase();
});

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

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', () => {
  expect(isCity('Vienna')).toBeTruthy();
});

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

Scoping

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', () => {
  expect(isCity('Vienna')).toBeTruthy();
});
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');
      expect(true).toEqual(true);
    });
  });

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

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

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

  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', () => {
  expect(true).toBe(false);
});

test('this test will not run', () => {
  expect('A').toBe('A');
});

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();
console.log(myMock());
// > undefined

myMock
  .mockReturnValueOnce(10)
  .mockReturnValueOnce('x')
  .mockReturnValue(true);

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="http://www.facebook.com">Facebook</Link>)
    .toJSON();
  expect(tree).toMatchSnapshot();
});

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

exports[`renders correctly 1`] = `
<a
  className="normal"
  href="http://www.facebook.com"
  onMouseEnter={[Function]}
  onMouseLeave={[Function]}
>
  Facebook
</a>
`;

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

Cheatsheet:

https://github.com/sapegin/jest-cheat-sheet/blob/master/Readme.md

https://devhints.io/jest

https://devhints.io/enzyme

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: https://reactjs.org/docs/context.html#dynamic-context

getDefaultProps

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.

componentWillMount()

Triggered before render().

componentDidMount

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.

render

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.

componentWillUnmount

Clean up event bindings, etc.

React CheatSheet

https://reactcheatsheet.com/

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
https://medium.com/@i_AnkurBiswas/pro-tips-for-visual-studio-code-to-be-productive-in-2018-d5252e914561
https://dev.to/seankilleen/vscode-tip-watching-files-1hkk

Shortcuts

mac: https://code.visualstudio.com/shortcuts/keyboard-shortcuts-macos.pdf
windows: https://code.visualstudio.com/shortcuts/keyboard-shortcuts-windows.pdf