How to debug jest test cases(React)?

Adding test cases to your code always helps in the long run, today we’re going to talk about how to debug test cases.

Do something today that your future self will thank you for

  1. Using our all time favourite Console.log
     it('should call touch & asyncValidate methods', () => {
          const component = shallow(
            <TrialRegistrationForm handleSubmit={mockHandleSubmit} pristine />,
          );
    
          const mockFunction = jest.fn();
          console.log(mockFunction);
          component.instance().touchAndAsyncValidate('test', '1');
    
          expect(mockFunction).toBeCalledWith('test');
        });
  2. Using the Jest recommend way by using node
      1. Add debugger; where we want to break our test case
      2. Run the command in terminal
        node --inspect-brk node_modules/.bin/jest --runInBand
        Debugger listening on ws://127.0.0.1:9229/c5ce34bb-64f3-4a59-8246-e21168ba8e26
        For help see https://nodejs.org/en/docs/inspector
      3. Open the link in chrome chrome://inspect
      4. Click on Open Dedicated DevTools for NodeDebug jest test cases
      5. Our script will break at the debugger

    debugger test cases react

How to update node to a given version

Scenario:- Update node to the given version ?

Solution:- 

Using nvm:-Node Version Manager

Install nvm 

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.8/install.sh | bash
  1. Reopen the terminal
  2. Check nvm is installed by typing nvm > enter > it will show nvm commands
  3. nvm install Node_Version_i_Want
$ nvm install 8.9.4

Note:- After installing the latest node incase your build fails with error like

Node Sass could not find a binding for your current environment: OS X 64-bit with Node.js 8.x

Solution is simply run the sass build npm rebuild node-sass

Working with prettier in Visual studio code

“Whenever you are confronted with an opponent, conquer them with love.”

What is prettier ?

In layman terms its an handy tool that will format our code against some set standards, default formatting rules to achieve consistent code style.

How to install prettier  in VS Code?

Search > Prettier – Code formatter

Prettier - Code formatter

Note:- Incase you have different IDE try installing prettier.

How to do perform user specific settings for prettier?

VS Code > File > Preferences > Settings > Under ‘user setttings’

vscode with prettier

 

 

 

 

 

    // Set the default prettier settings
    "editor.formatOnSave": false,
    "prettier.singleQuote": true,
    "prettier.trailingComma": "all",
    // Enable per-language
    "[javascript]": {
        "editor.formatOnSave": true
    }

Most Useful Git commands

I have decided to stick with love. Hate is too great a burden to bear.

  1. List all the branches : git branch
  2. Pull the recent changes: git pull
  3. Create a feature branch : git checkout -b <new branch name> <parent branch name>
  4. Delete branch local: git branch -d <branch-name> or git branch -D <branch-name>
  5. Delete branch from remote : git push origin –delete <branch_name>
  6. See all remote branches: git branch -v -a
  7. Get conflicted list of files: git diff –name-only –diff-filter=U
  8. git fetch origin (checkout new remote branch)
    1. git checkout -t origin/remote-branch
  9. List all remote branches: git branch -r ()

How to add CSS modules into your react Application?

“Believe in yourself && Keep Learning”

Step1:- In our example we have take “create-react-app” template as reference. Install this and than perform “yarn eject

What is yarn eject:- it will give you control of the create-react-app and you can install or play with config settings or package.json file.

Step2:- Search for “css-loader” inside the file “config/webpack.config.dev.js” and enable CSS modules in this.

Before:-

 require.resolve('style-loader'),
              {
                loader: require.resolve('css-loader'),
                options: {
                  importLoaders: 1,
                },
              },

After:-

              require.resolve('style-loader'),
              {
                loader: require.resolve('css-loader'),
                options: {
                  importLoaders: 1,
                  modules: true,
                  localIdentName: "[name]__[local]___[hash:base64:5]"
                },
              },

Step3:- Change it for production file also(“config/webpack.config.prod.js” )

Before:-

  loader: require.resolve('css-loader'),
                      options: {
                        importLoaders: 1,
                        minimize: true,
                        sourceMap: shouldUseSourceMap,
                      },

After:-

                    {
                      loader: require.resolve('css-loader'),
                      options: {
                        importLoaders: 1,
                        modules: true,
                        minimize: true,
                        sourceMap: shouldUseSourceMap,
                      },
                    },

Step4:-Implementing CSS modules,

use >  import styes from ‘filename’ and than className={styles.class}

import React, { Component } from 'react';
import PropTypes from 'prop-types';

import styles from './ToolTip.css';

export default class ToolTip extends Component {
    static displayName = "ToolTip";

    static propTypes= {
        children: PropTypes.node.isRequired,
    }

    render(){
        const {children} = this.props;
        return(
            <div className={styles.header}>
               {children}
            </div>
        );
    }
}

Step5:- yarn start
Now React app is happily married to CSS modules.

Note:- Incase you are facing issue with using global classes and CSS modules together you can use “ClassNames”

Example code using both css modules and global classes.

import classnames from 'classnames';
import styles from './test.module.scss';
<Button
          className={classnames('button', 'button-primary', styles.login)}
          type="submit"
        >
Test Button
</Button>

How to check that javascript object contains the given key?

A wet man does not fear the rain.

Issue:-How do I check if an object has a key in JavaScript?

Example:-

// Sample Object
const REMINDER = "REMIND_ME";
reminderObj= {
INBOX:`${REMINDER}_INBOX`,
USERS:`${REMINDER}_USERS`,
GROUPS:`${REMINDER}_GROUPS`,
}

Problem1: Now we want to check that our object have “INBOX” as key or not?

Solution:- 

Object.prototype.hasOwnProperty.call(reminderObj,"INBOX");
Note:- We could directly use hasOwnProperty but to avoid eslint errors we have used the longer syntax as above.

Problem2: Now we want to check what is the value for given key say “INBOX” inside our object?

const reminderLocation = "INBOX";

reminderObj[reminderLocation];

or
reminderObj.INBOX;

 javascript object

Handy tips and Tools for working with wordpress -Part2?

“The best teachers are those who show you where to look, but don’t tell you what to see.”

1.How to add text-slider in wordpress pages ?
Solution:-
By using the “Text slider plugin

Activate the plugin > Add the Main and Sub text > Configure the settings > add the wp_text_slider();
?> in the code where you want to add this effect.

2.How to send contact email in wordpress ?
Solution:-
By using the “WCP contact” plugin

Activate the plugin > Add the Main and Sub text > Configure the settings > add the ;
?> in the shortcode like [wcp_contactform id=”wcpform_1″] where you want to add this form.

Note for sending the email to your email inbox you need to add the “SMTP plugin” else above plugin will show email messages inthe wordpress itself.

Not able to receive email using WCP contact plugin.

3.How to redirect page not found(404) to home page of website?
Solution:-
Incase you dont want to desing the 404 page, just follow the below code to redirect user to home page.

1.Open your 404.php page  (incase its not present use create one inside the themes folder )
2.Add the below lines of code, publish and you are done

<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: ".get_bloginfo('url'));
exit();
?>

4.How to add carousel slider for the featured posts?
Solution:-
1.Using “carosuel slider“, add the plugin and select the option as post.

5.How to add Team member page in wordpress?
Solution:-
1.Using “Team member showcase plugin“, add the plugin and explore the free styles available.

More wordpress tips.

How to use FormattedMessage for input placeholder in React?

Problem:- How we can translate the placeholder text for input-box using formatmessage?

Translate placeholder text in react


Solution:-
If we use react-intl its not meant to be used with  placeholders, alternate text, etc. They render HTML, not plain text, which is not useful in our scenario.

1. Incase we have one or two values to translate, we can use FormattedMessage as wrapper as shown in below code, 

import { FormattedMessage } from 'react-intl';

        <FormattedMessage id="SEARCH_FOR_GROUPS">
          { placeholder =>
            <input
              className="search-filter"
              disabled={allGroups}
              onChange={this.handleSearchChange}
              placeholder={placeholder}
              ref={(input) => { this.textInput = input; }}
              type="text"
              value={searchText}
            />
          }



2.We can also use injectIntl api for achieving the same incase we need more translations to perform.

Note:- We can also use FormattedHTMLMessage incase our strings needs to be interpreted as HTML say it contains anchor tag <a href=”#” />

import {  FormattedHTMLMessage } from 'react-intl';

 <div className={styles.Header}>
        <FormattedHTMLMessage id="ERROR_PAGE_CONTENT" />
 </div>

Learn more and share more 🙂