How to Invoice Your Clients Professionally (10 Tips)

Original Source: https://www.hongkiat.com/blog/invoice-freelance-clients-professionally/

Let’s face it – while receiving money can be very addictive, invoicing is a total nightmare for freelancers, especially designers. However, the freelance business’s truth is that…

Visit hongkiat.com for full content.

How to Ensure Flexible, Reusable PHP Code with Insphpect

Original Source: https://www.sitepoint.com/how-to-ensure-flexible-reusable-php-code-with-insphpect/?utm_source=rss

Insphpect is a tool I wrote as part of my PhD project. It scans code for object-oriented programming techniques that hinder code reusability and flexibility.

Why?

Let me begin with two mundane observations:

Business requirements change over time.
Programmers are not clairvoyant.

New product launches, emergency lockdown regulations, expanding into new markets, economic factors, updated data protection laws: there are lots of potential causes for business software to need updating.

From those two observations we can infer that programmers know that the code they write is going to change, but not what those changes will be or when they will happen.

Writing code in such a way that it can be easily adapted is a skill that takes years to master.

You’re probably already familiar with programming practices that come back and haunt you. Novice programmers quickly realize that global variables are more trouble than they’re worth, and the once incredibly popular Singleton Pattern has been a dirty word for the last decade.

How you code your application has a big impact on how easy it is to adapt to meet new requirements. As you progress through your career, you learn techniques that make adapting code easier. Once you’ve grasped fundamentals of object-oriented programming you wonder how you ever did without it!

If you ask ten developers to produce software, given the same requirements, you’ll get ten different solutions. Some of those solutions will inevitably be better than others.

Consider a ship in a bottle and a model ship made of Lego. Both are model ships, but changing the sails on the ship in a bottle is very difficult, and reusing the parts is near impossible. However, with a Lego ship, you can easily swap out the sails or use the same components to build a model rocket, house or a car.

Certain programming techniques lead to the ship-in-a-bottle approach and make your code difficult to change and adapt.

Insphpect

Insphpect is a tool which scans your code for programming practices that lead to this kind of a ship in a bottle design.

It grades your code based on how flexible it is, and highlights areas where flexibility can be improved.

What does Insphpect look for?

Currently, Insphpect looks for the following:

tight coupling
hardcoded configuration
singletons
setter injection
using the new keyword in a constructor
service locators
inheritance
static methods
global state
files that have more than one role (e.g. defining a class and running some code)

If it detects anything it identifies as inflexible, it highlights the code, explains why it highlighted the issue, then grades your whole project and individual classes on a score of 0-100 (with 100 being no issues detected). As a proof of concept, for some detections it’s able to automatically generate a patch file that re-writes the code to remove the inflexibility entirely.

Take a look a sample report here.

Insphpect is currently in the testing phase, and it would really help my research progress if you can check it out and complete the survey in the “Give your feedback” section of the site.

Background

Are those bad practices really bad, though?

This was one of the more difficult parts of the background research, and you can read about how this was done in detail on the Insphpect website.

However, this can be summarized as:

The opinions of each bad practice were collected from 100 authors per practice.
The author’s opinion on the practice was graded on a scale of 1–5.
The author’s methodological rigor was graded on a scale of 1–7 based on the Jadad score used for clinical trials.

These were then plotted like the graph below:

Singleton pattern results

Each horizontal line represents an article, and the left (orange) bar for each article is the recommendation going from 5 — Avoid this practice at all costs (Far left) — to 1 — Favor this practice over alternatives.

The right (blue) bar for each article is the Jadad style score measuring analytic rigor. A score of seven means the article describes the practice, provides code examples, discusses alternative approaches, provides like-for-like code samples, discusses the pros/cons of each approach and makes a recommendation of which approach should be used.

In the case of the singleton above, authors who compare the singleton to alternative approaches, discuss the pros/cons, etc., are significantly more likely to suggest using alternative approaches.

Walkthrough

Currently, Insphpect allows uploading code via a Git repository URL or a ZIP file.

So not to point out flaws in other people’s work, let’s take a look at one of my own projects to see what it identifies.

We’ll use https://github.com/Level-2/Transphporm as an example project.

This is quite a good example, because it has a very high score on another code-quality tool Scrutinizer.

Firstly, enter the git URL https://github.com/Level-2/Transphporm into the text box at the top of the home page and press “Go”. It will take a few seconds to minutes, depending on the size of the project, and will generate a report that looks something like this:

Transphporm Report

Once you’re on the report page, you’ll see a summary at the top with an overall grade out of 100, with 100 being very good and 0 being very poor.

Underneath the summary, you’ll see a list of all the classes in the project, each with its own grade.

Don’t worry if your code doesn’t get a perfect score. It’s unlikely that it will. Remember, Insphpect is a tool that identifies flexibility in your code. There are parts of your code (like the entry point) where flexibility isn’t warranted.

For Transphporm, it has highlighted issues in seven classes.

Let’s take a look at some of those. Scroll down to TransphpormParserCssToXpath and click the link. You’ll see a score for that particular class and a list of issues which have been identified.

In this case, it has identified a static variable and a static method. Clicking on one of the red lines will reveal an explanation of why the line was flagged up.

For example, clicking line 12 will give an explanation of why static variables are less flexible than instance variables.

Single class report

Although there’s a more in-depth explanation of the issues caused by static properties on the report, as a quick refresher, static variables have one value which is shared across all the instances of the class.

This is inherently less flexible than an instance variable, because using an instance variable allows each instance to have a different value.

For example, consider the following:

class User {
public static $db;
public $id;
public $name;
public $email;

public function save() {
$stmt = self::$db->prepare(‘REPLACE INTO user (id, name, email) VALUES (:id, :name, :email)’);

$stmt->execute([
‘id’ => $this->id,
‘name’ => $this->name.
’email’ => $this->email
]);
}
}

Because $db is static, every instance of this class shares the same $db instance and records will always be inserted into the same database.

While this sounds reasonable, let me give you a real-world example.

Continue reading
How to Ensure Flexible, Reusable PHP Code with Insphpect
on SitePoint.

15 React Interview Questions with Solutions

Original Source: https://www.sitepoint.com/react-interview-questions-solutions/?utm_source=rss

15 React Interview Questions with Solutions

React’s popularity shows no sign of waning, with the demand for developers still outstripping the supply in many cities around the world. For less-experienced developers (or those who’ve been out of the job market for a while), demonstrating your knowledge at the interview stage can be daunting.

In this article, we’ll look at fifteen questions covering a range of knowledge that’s central to understanding and working effectively with React. For each question, I’ll summarize the answer and give links to additional resources where you can find out more.

1. What’s the virtual DOM?
Answer

The virtual DOM is an in-memory representation of the actual HTML elements that make up your application’s UI. When a component is re-rendered, the virtual DOM compares the changes to its model of the DOM in order to create a list of updates to be applied. The main advantage is that it’s highly efficient, only making the minimum necessary changes to the actual DOM, rather than having to re-render large chunks.

Further reading

Understanding the Virtual DOM
Virtual DOM Explained

2. What’s JSX?
Answer

JSX is an extension to JavaScript syntax that allows for writing code that looks like HTML. It compiles down to regular JavaScript function calls, providing a nicer way to create the markup for your components.

Take this JSX:

<div className=”sidebar” />

It translates to the following JavaScript:

React.createElement(
‘div’,
{className: ‘sidebar’}
)

Further reading

What is JSX?
JSX in Depth
JSX in React Design Patterns and Best Practices

3. What’s the difference between a class component and a functional one?
Answer

Prior to React 16.8 (the introduction of hooks), class-based components were used to create components that needed to maintain internal state, or utilize lifecycle methods (i.e. componentDidMount and shouldComponentUpdate). A class-based component is an ES6 class that extends React’s Component class and, at minimum, implements a render() method.

Class component:

class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}

Functional components are stateless (again, < React 16.8) and return the output to be rendered. They are preferred for rendering UI that only depends on props, as they’re simpler and more performant than class-based components.

Functional component:

function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}

Note: the introduction of hooks in React 16.8 means that these distinctions no longer apply (see questions 14 and 15).

Further reading

Functional Components vs Class Components in React
Functional vs Class-Components in React

4. What are keys used for?
Answer

When rendering out collections in React, adding a key to each repeated element is important to help React track the association between elements and data. The key should be a unique ID, ideally a UUID or other unique string from the collection item, but which can be an array index as a last resort:

<ul>
{todos.map((todo) =>
<li key={todo.id}>
{todo.text}
</li>
)};
</ul>

Not using a key can result in strange behavior when adding and removing items from the collection.

Further reading

Lists and Keys
Understanding React’s key prop

5. What’s the difference between state and props?
Answer

props are data that are passed into a component from its parent. They should not be mutated, but rather only displayed or used to calculate other values. State is a component’s internal data that can be modified during the lifetime of the component, and is maintained between re-renders.

Further reading

props vs state

6. Why call setState instead of directly mutating state?
Answer

If you try to mutate a component’s state directly, React has no way of knowing that it needs to re-render the component. By using the setState() method, React can update the component’s UI.

Bonus

As a bonus, you can also talk about how state updates are not guaranteed to be synchronous. If you need to update a component’s state based on another piece of state (or props), pass a function to setState() that takes state and props as its two arguments:

this.setState((state, props) => ({
counter: state.counter + props.increment
}));

Further reading

Continue reading
15 React Interview Questions with Solutions
on SitePoint.

How to Keep Working Remotely in a Post-COVID-19 World

Original Source: https://www.sitepoint.com/post-covid-19-remote-work/?utm_source=rss

How To Keep Working Remotely in a post-COVID-19 World

Though the COVID-19 pandemic is still far from over, many companies and employees are already looking to the post-COVID world. For many organizations, the enforced move to remote working over the past few months has presented significant challenges.

On the other hand, there are many employees who, despite being reticent to move to remote working at the beginning of the pandemic, are now finding that remote work actually suits them rather well.

If you fall into this category, you might be wondering how you can continue to work from home after the current crisis ends. Many of the strategies you can deploy to achieve this are, in fact, similar to those that make for effective remote working in the first place: ensuring effective collaboration in remote teams, and making sure that you set yourself up for success with remote work, to name a couple things.

Nevertheless, your employer might be hesitant to let you continue to work remotely after the pandemic is over. If you don’t want to move back to the office, you’ll find some tips in this article on how to convince your boss to let you continue working from home.

The Benefits of Remote Working

If you don’t want to move back to your office in the next few months, you’re not alone. In fact, nearly 43% of full-time American employees say they want to work remotely more often even after the economy has reopened. One of the biggest reasons for this is the time that the average tech worker saves in commuting. The average American spent roughly 27 minutes on their one-way commute to the office in 2018, which equates to more than 200 hours spent commuting per year.

For tech companies, there are other benefits of remote working. Many software development firms are inherently multi-national, and co-ordinating employees across the globe can actually be easier if they’re working from home. As we’ve previously pointed out, the future of remote work is asynchronous. Research has also found that the kind of creativity and flexibility that tech firms value is actually increased by remote working rather than decreased.

Despite these findings, many organizations are still hesitant to let their employees work from home — at least once the global health crisis is over. So how can you continue to work from home after all this is over?

Continue reading
How to Keep Working Remotely in a Post-COVID-19 World
on SitePoint.

This Week In Web Design – June 26, 2020

Original Source: http://feedproxy.google.com/~r/1stwebdesigner/~3/wXFGQBC-8q8/

It’s the last Friday of June – how did we get here so fast? Friday at 1stWebDesigner means it’s time for this week’s edition of “This Week In Web Design”, our roundup of all the web design and development articles we’ve found that have been published in the past seven days. This week’s list includes UX design and testing, GitHub, JavaScript, WordPress, CSS, ways to get clients, and more! Let’s have a look!

Web Designer Toolbox: Unlimited Downloads Starting at $16.50/Month

Website Kits

Website Kits
16,000+ Web Designs

UX & UI Kits

UX & UI Kits
14,000+ UX & UI Kits

Graphic Assets

Graphic Assets
33,000+ Graphics

DOWNLOAD NOW
Envato Elements

What Is User Experience (UX) Testing? [+4 UX Best Practices]

User experience (UX) testing can help you analyze your site to ensure you’re providing a great experience for your audience.

Using 6 Google Analytics Features to Improve User Experience and Website Metrics

Two subsets of what you can use Google Analytics for as a UX designer: user behavior and user intent.

How (And Why) to Design for Local Businesses

When you take a small business client, your approach to design will likely be a little different. Here’s how to think about it.

JavaScript If Else Statement Made Simple

This tutorial will help you learn all you need to know about if else statement. You will learn how to use if, else, else if and nested if else.

Staying creative during hard times—and why it matters now more than ever

If we’re not creating anything when we’re suffering, there might not be anything tangible to look back upon.

How To Migrate a WordPress Website

All the ways you can migrate your WordPress site – manually and with plugins – can be found here.

Using Custom Property “Stacks” to Tame the Cascade

Use Custom Property “stacks” to solve some of the common issues people face in the cascade: from scoped component styles, to more explicit layering of intents.

Learn GitHub CLI: Your Guide to GitHub from the Command Line

In this quickstart guide, you’ll learn GitHub CLI. Find out what the GitHub CLI tool is used for, how to set it up, and how to use it.

Awesome Demos Roundup #16

The newest roundup of fantastic demos and web experiments from around the web.

12 Freelance Web Developer Jobs Sites to Get New Dev Clients

Knowing where to find high-quality freelance web developer jobs is critical to keeping your freelance dev business thriving.

Simple Design Tips for Crafting Better UI Cards

In this article, we will review the concept of cards and share some practical tips for designers.

An Overview of Scroll Technologies

An overview of scroll-related technologies and tools to help choose the one that’s right for you.

Examples of Creative Contact and Web Form Designs

Let us consider some good tips on how to create web form designs that are pleasant to use, accessible, secure & easily convertible.

How Web Designers Can Help Restaurants Move Into Digital Experiences

Restaurants are going to need web designers’ help in doing three things that ensure their survival in an increasingly digital world.

Best Design System Tools (Free & Premium)

Are you looking for design system tools to help you out with your next project? If yes, then you are in the right place.

Design Trend: Geo Shapes & Patterns (With Animation)

Stylish geometry is a design trend that keeps coming back around. This time the new twist is that shapes and design elements include touches of animation to bring shapes and patterns to life.

Accessibility and inclusion in UX for Product Managers

A disability is a phenomenon reflecting the interaction between features of a person’s body and features of the society in which he or she lives.

How To Add reCAPTCHA v3 to PHP Form and Submit Using Ajax

In this tutorial, we will add Google reCAPTCHA v3 to a PHP form and submit it without leaving the page, using Ajax.

A Glitchy Grid Layout Slideshow

An experimental grid slideshow with a stack-like navigation and glitch effect.

11,000+
Icons

20,000+
Illustrations

Envato Elements

DOWNLOAD NOW

14,000+
UI & UX Kits

16,000+
Web Templates

Highlight Text CSS: 7 Cool CSS Highlight Text Effects

In this short tutorial I will show you several cool ways in which you can use CSS to highlight text.

On racism and sexism in branding, user interface, and tech

Take a look at some unfortunate design, copy, and tech decisions made by massive international brands.

Hide Scrollbars During an Animation

Use @keyframes not to animate the opening, but just for this scrollbar-hiding functionality.

How to Present a Logo to Clients in 6 Steps (Tips from Experts)

A collection of incredible advice from experienced logo designers who have been designing logos and presenting them to clients for years.

Skeuomorphism is making a comeback

Today with even more certainty, I’ll say it again: skeuomorphism is coming back in web design.

15 React Interview Questions with Solutions

For less-experienced developers (or those who’ve been out of the job market for a while), demonstrating your knowledge at the interview stage can be daunting.

The Importance of Documentation for Web Developers

Although it can be burdensome, writing documentation is important and will deliver advantages for your users, your colleagues, and especially yourself.

How to write an effective design brief in 9 easy steps

A 9-step plan to create an effective brief that helps you deliver a new design to your client.

How to Enhance Your Website Layouts With SVG Shapes

Get rid of the usual boring rectangular boxes and learn to build a landing page full of complex SVG shapes.

How to get web design clients

One of the biggest challenges as a freelance designer isn’t the work itself. It’s finding clients.


Cinema 4D Visual Explorations by David Milan

Original Source: http://feedproxy.google.com/~r/abduzeedo/~3/11aXY9bgeD4/cinema-4d-visual-explorations-david-milan

Cinema 4D Visual Explorations by David Milan
Cinema 4D Visual Explorations by David Milan

AoiroStudio06.25.20

Here at abdz., we love 3D and Cinema 4D. I don’t generally have the dedicated time to get into 3D so we feature the incredible designers/artists to feast your eyes. That being said and following this route, let’s take a look at these 3D explorations by David Milan . David is the ‘creative type’ to push its boundaries and explore with lights, textures, shapes, colours through its work. What we are featuring is his series titled: EXPERIMENTYPE VOL. 2 and enjoy!

Links

http://www.davidmilan.com
https://www.behance.net/DavidMilan


Are You a Designer? Here’s What You Need to Know About the Laws!

Original Source: http://feedproxy.google.com/~r/Designrfix/~3/8cBvRPUrSr4/are-you-a-designer-heres-what-you-need-to-know-about-the-laws

As a designer, your creativity has its limits and there are times it’s necessary to refer to different sources for inspiration.  It’s important that you understand the laws with regards to using another person’s art. Failure to do so could cause you to face legal repercussions if losing your reputation isn’t bad enough.  Furthermore, understanding […]

The post Are You a Designer? Here’s What You Need to Know About the Laws! appeared first on designrfix.com.

How To Migrate a WordPress Website

Original Source: http://feedproxy.google.com/~r/1stwebdesigner/~3/dhBThR3yQSw/

If you have a WordPress (or any other type of) website for any length of time, it’s likely you’ll run into the need to move it to a new host at some point. Figuring out how to migrate a WordPress website is one of those site maintenance tasks a lot of people would rather avoid as it can seem unruly, unpredictable, and time-consuming.

And sometimes, it really is all of those things. However, if you plan ahead and have a good set of instructions to walk you through the process, you should be good to go.

2100+ WordPress Themes, Plugins, Templates: ONLY $16.50 per Month

WordPress Themes

WP Themes
1,200+ Themes

WordPress Plugins

WP Plugins
500+ Plugins

WP Template Kits

WP Template Kits
250+ Template Kits

DOWNLOAD NOW
Envato Elements

Why Migrate?

Site owners find they need to migrate WordPress sites for a number of different reasons. A lot of the time, it’s a matter of finding a better hosting deal elsewhere. The promise of saving money is always enticing. Another common reason to migrate your site is due to a lack of satisfaction with your current service provider. Whether they offer poor customer service or slow server response times, there are many reasons to switch.

Here are a few more common reasons people decide to migrate a WordPress website:

Seeking better site performance. If your site is currently too slow, an upgrade to a new host might be the right call.
A need for greater bandwidth. If your site is growing rapidly, migrating to a host that can handle your increased traffic needs is a must.
A need for more storage space. If your site is multimedia-heavy, migrating to a host with greater storage capacity might be the right choice for you.
More hands-on customer support. If you run an extensive website with a lot of moving parts (customers, clients, accounts, etc), the need for a more responsive customer support team might be more pronounced and necessary.
Better pricing. Sometimes, the price tag tells the whole story. If you find a better hosting deal elsewhere, migrating your WordPress site might be your best bet.
Expanded feature set. If your current host is lacking in features, you may find you need to migrate to one that offers more.

With the “why” spelled out, let’s move onto the “how.” We’ll cover how to manually migrate WordPress, along with some plugins that will do the hard work for you.

A truck on a street.

How to Manually Migrate a WordPress Site

You will need an FTP client to complete this process. A few options include:

FileZilla
CyberDuck
CuteFTP
FreeFTP

Step 1: Backup Your Site

Before you can move your site anywhere, you need to back it up. This means going through the process of downloading every single file of your WordPress site from a remote location. You will need an FTP client for this. Though I typically use FileZilla for this process, I’ll keep the steps fairly generic. Apply as needed to your chosen FTP client:

Connect to your old site’s server.
Go to the public_html folder.
Select all files in this folder.
Download the files.

Next, you’ll need to create and download a backup of your site’s MySQL database as well. To do this, you’ll need to go to the control panel of your web host. Most of the time, this will be cPanel. Go to phpMyAdmin and select the database associated with your WordPress site. Click Export and the database will be downloaded to your computer.

If you’d rather have this process be somewhat automated, go to cPanel (if your host supports it) and access the File Manager. In here, you can create a .zip file that contains all of your site’s files and its database for easy downloading. If you’re not super familiar with FTP, this might be the preferred method to use.

Step 2: Upload Your Files to the New WordPress Host

The next step to migrate a WordPress website is to upload your site’s files to the new host. You’ll need your trusty FTP client again. Once connected, you’ll need to go to the public_html folder on this new hosting account. Next, you’ll need to upload all the files from your site – make sure to decompress them first!

Step 3: Upload Your WordPress Database to the New Host

Once the files are uploaded, you’ll need to upload your WordPress MySQL database, too.

To do this, go to the cPanel or other control panel connected to your new hosting account. There should be a section specifically for MySQL databases. From there you’ll need to:

Create a new database. Make note in a safe place of the database name, username, and password associated with this new database.
Go to phpMyAdmin. The new database should be listed. Select it.
Click Import. Then, select the MySQL database file you’d previously downloaded. Upload it and save your settings.

Step 4: Edit the wp-config.php File

Now that everything has been uploaded to the new host, you’ll need to do some fine-tuning to ensure all of the new host’s settings work with your site. This will require using your FTP client again, but this time, find the wp-config.php file.

Once you’ve located this file, you’ll need to modify some code. According to SiteGround, you need to locate this section of code within the file:

/** The name of the database for WordPress */
define(‘DB_NAME’, ‘user_wrdp1’);

/** MySQL database username */
define(‘DB_USER’, ‘user_wrdp1’);

/** MySQL database password */
define(‘DB_PASSWORD’, ‘password’);

/** MySQL hostname */
define(‘DB_HOST’, ‘hostname’);

Once you’ve located this section of code, you need to replace bits of it with information about the WordPress database you created. Here’s what you need to replace:

Change the database name, if necessary
Set username to your database’s username
Set password to your database’s password
Swap out hostname for localhost or a custom name provided by your host

Save the changes you made. In a lot of cases, this will be the last step you need to take. Your site should now be up and running on the new host.

Step 5: Update the DNS

In some cases, you’ll need to update Domain Name Server or DNS information on your new host. This will ensure that when someone types in your site’s URL, they wind up on your actual site and not a blank page. This is common practice when you’re switching domain servers, hosting plans, and hosting companies.

According to WPEngine, you’ll need DNS info about your new host and access to the registrar from whom you bought your domain name in the first place. Specifically, you’ll need:

CNAME record
A NAME for your site.

Input this info in your domain registrar account. This can sometimes take up to a few days to complete processing.

11,000+
Icons

20,000+
Illustrations

Envato Elements

DOWNLOAD NOW

14,000+
UI & UX Kits

16,000+
Web Templates

Plugins for Migrating WordPress Sites

If all of the above sounds like a lot of work, you can rely on plugin-based solutions to do the heavy lifting for you. These plugins are sometimes referred to as “cloning” plugins but for our purposes, we’re considering them all methods of migrating WordPress websites.

Now, you will still likely need to adjust a few settings on your new site server manually, but these plugins will definitely take care of the backing up, exporting, and importing processes.

Duplicator

Duplicator WordPress Plugin

The Duplicator plugin makes it much easier to migrate WordPress by streamlining the process. It works by making click-of-a-button copies of your site’s files and database. Then you can download all of this information in a handy .zip file with minimal effort.

All-in-One WP Migration

All-in-One WP Migration WordPress Plugin

Another great option is the All-in-One WP Migration plugin. This one allows you to make backups of your site’s content and database as well and import this information over to your new host, all from within the plugin.

WP Engine Automated Migration

WP Engine Automated Migration WordPress Plugin

Our last recommendation is the WP Engine Automated Migration plugin. This one copies your files and WordPress database and allows you to upload them to your new site server with ease. So long as you have your hosting account details on hand, the plugin will handle much of the site migration process for you. Just note that this plugin only works with the WP Engine hosting provider.

Migrate Your Site Now

Whether you decide to migrate a WordPress site manually or you opt for the plugin route, you hopefully now have a stronger understanding of what the process entails, how it works, and what you need to do to prepare. Again, it might seem like a lot of work on the surface but the end result is often well worth it when you end up with a better home for your website.

Best of luck!


Practical Guide To Testing React Applications With Jest

Original Source: https://www.smashingmagazine.com/2020/06/practical-guide-testing-react-applications-jest/

Practical Guide To Testing React Applications With Jest

Practical Guide To Testing React Applications With Jest

Adeneye David Abiodun

2020-06-24T12:00:00+00:00
2020-06-24T20:35:26+00:00

In this article, I’m going to introduce you to a React testing tool named Jest, along with the popular library Enzyme, which is designed to test React components. I’ll introduce you to Jest testing techniques, including: running tests, testing React components, snapshot testing, and mocking.
If you are new to testing and wondering how to get started, you will find this tutorial helpful because we will start with an introduction to testing. By the end, you’ll be up and running, testing React applications using Jest and Enzyme. You should be familiar with React in order to follow this tutorial.

A Brief Introduction To Testing

Testing is a line-by-line review of how your code will execute. A suite of tests for an application comprises various bit of code to verify whether an application is executing successfully and without error. Testing also comes in handy when updates are made to code. After updating a piece of code, you can run a test to ensure that the update does not break functionality already in the application.

Why Test?

It’s good to understand why we doing something before doing it. So, why test, and what is its purpose?

The first purpose of testing is to prevent regression. Regression is the reappearance of a bug that had previously been fixed. It makes a feature stop functioning as intended after a certain event occurs.
Testing ensures the functionality of complex components and modular applications.
Testing is required for the effective performance of a software application or product.

Testing makes an app more robust and less prone to error. It’s a way to verify that your code does what you want it to do and that your app works as intended for your users.

Let’s go over the types of testing and what they do.

Unit Test

In this type of test, individual units or components of the software are tested. A unit might be an individual function, method, procedure, module, or object. A unit test isolates a section of code and verifies its correctness, in order to validate that each unit of the software’s code performs as expected.

In unit testing, individual procedures or functions are tested to guarantee that they are operating properly, and all components are tested individually. For instance, testing a function or whether a statement or loop in a program is functioning properly would fall under the scope of unit testing.

Component Test

Component testing verifies the functionality of an individual part of an application. Tests are performed on each component in isolation from other components. Generally, React applications are made up of several components, so component testing deals with testing these components individually.

For example, consider a website that has different web pages with many components. Every component will have its own subcomponents. Testing each module without considering integration with other components is referred to as component testing.

Testing like this in React requires more sophisticated tools. So, we would need Jest and sometimes more sophisticated tools, like Enzyme, which we will discuss briefly later.

Snapshot Test

A snapshot test makes sure that the user interface (UI) of a web application does not change unexpectedly. It captures the code of a component at a moment in time, so that we can compare the component in one state with any other possible state it might take.

We will learn about snapshot testing in a later section.

Advantages and Disadvantages of Testing

Testing is great and should be done, but it has advantages and disadvantages.

Advantages

It prevents unexpected regression.
It allows the developer to focus on the current task, rather than worrying about the past.
It allows modular construction of an application that would otherwise be too complex to build.
It reduces the need for manual verification.

Disadvantages

You need to write more code, as well as debug and maintain.
Non-critical test failures might cause the app to be rejected in terms of continuous integration.

Introduction to Jest

Jest is a delightful JavaScript testing framework with a focus on simplicity. It can be installed with npm or Yarn. Jest fits into a broader category of utilities known as test runners. It works great for React applications, but it also works great outside of React applications.

Enzyme is a library that is used to test React applications. It’s designed to test components, and it makes it possible to write assertions that simulate actions that confirm whether the UI is working correctly.

Jest and Enzyme complement each other so well, so in this article we will be using both.

Process Of Running A Test With Jest

In this section, we will be installing Jest and writing tests. If you are new to React, then I recommend using Create React App, because it is ready for use and ships with Jest.

npm init react-app my-app

We need to install Enzyme ****and enzyme-adapter-react-16 with react-test-renderer (the number should be based on the version of React you’re using).

npm install –save-dev enzyme enzyme-adapter-react-16 react-test-renderer

Now that we have created our project with both Jest and Enzyme, we need to create a setupTest.js file in the src folder of the project. The file should look like this:

import { configure } from “enzyme”;
import Adapter from “enzyme-adapter-react-16”;
configure({ adapter: new Adapter() });

This imports Enzyme and sets up the adapter to run our tests.

Before continuing, let’s learn some basics. Some key things are used a lot in this article, and you’ll need to understand them.

it or test
You would pass a function to this method, and the test runner would execute that function as a block of tests.
describe
This optional method is for grouping any number of it or test statements.
expect
This is the condition that the test needs to pass. It compares the received parameter to the matcher. It also gives you access to a number of matchers that let you validate different things. You can read more about it in the documentation.
mount
This method renders the full DOM, including the child components of the parent component, in which we are running the tests.
shallow
This renders only the individual components that we are testing. It does not render child components. This enables us to test components in isolation.

Creating A Test File

How does Jest know what’s a test file and what isn’t? The first rule is that any files found in any directory with the name __test__ are considered a test. If you put a JavaScript file in one of these folders, Jest will try to run it when you call Jest, for better or for worse. The second rule is that Jest will recognize any file with the suffix .spec.js or .test.js. It will search the names of all folders and all files in your entire repository.

Let’s create our first test, for a React mini-application created for this tutorial. You can clone it on GitHub. Run npm install to install all of the packages, and then npm start to launch the app. Check the README.md file for more information.

Let’s open App.test.js to write our first test. First, check whether our app component renders correctly and whether we have specified an output:

it(“renders without crashing”, () => {
shallow(<App />);
});

it(“renders Account header”, () => {
const wrapper = shallow(<App />);
const welcome = <h1>Display Active Users Account Details</h1>;
expect(wrapper.contains(welcome)).toEqual(true);
});

In the test above, the first test, with shallow, checks to see whether our app component renders correctly without crashing. Remember that the shallow method renders only a single component, without child components.

The second test checks whether we have specified an h1 tag output of “Display Active User Account” in our app component, with a Jest matcher of toEqual.

Now, run the test:

npm run test
/* OR */
npm test

The output in your terminal should like this:

PASS src/App.test.js
√ renders without crashing (34ms)
√ renders Account header (13ms)

Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 11.239s, estimated 16s
Ran all test suites related to changed files.

Watch Usage: Press w to show more.

As you can see, our test passed. It shows we have one test suite named App.test.js, with two successful tests when Jest ran. We’ll talk about snapshot testing later, and you will also get to see an example of a failed test.

Skipping Or Isolating A Test

Skipping or isolating a test means that when Jest runs, a specific marked test is not run.

it.skip(“renders without crashing”, () => {
shallow(<App />);
});

it(“renders Account header”, () => {
const wrapper = shallow(<App />);
const header = <h1>Display Active Users Account Details</h1>;
expect(wrapper.contains(header)).toEqual(true);
});

Our first test will be skipped because we’ve used the skip method to isolate the test. So, it will not run or make any changes to our test when Jest runs. Only the second one will run. You can also use it.only().

It’s a bit frustrating to make changes to a test file and then have to manually run npm test again. Jest has a nice feature called watch mode, which watches for file changes and runs tests accordingly. To run Jest in watch mode, you can run npm test — –watch or jest –watch. I would also recommend leaving Jest running in the terminal window for the rest of this tutorial.

Mocking Function

A mock is a convincing duplicate of an object or module without any real inner workings. It might have a tiny bit of functionality, but compared to the real thing, it’s a mock. It can be created automatically by Jest or manually.

Why should we mock? Mocking reduces the number of dependencies — that is, the number of related files that have to be loaded and parsed when a test is run. So, using a lot of mocks makes tests execute more quickly.

Mock functions are also known as “spies”, because they let you spy on the behavior of a function that is called directly by some other code, rather than only testing the output.

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

Manual mocks ****are used to stub out functionality with mock data. For example, instead of accessing a remote resource, like a website or a database, you might want to create a manual mock that allows you to use fake data.

We will use a mock function in the next section.

Testing React Components

The section will combine all of the knowledge we have gained so far in understanding how to test React components. Testing involves making sure the output of a component hasn’t unexpectedly changed to something else. Constructing components in the right way is by far the most effective way to ensure successful testing.

One thing we can do is to test components props — specifically, testing whether props from one component are being passed to another. Jest and the Enzyme API allow us to create a mock function to simulate whether props are being passed between components.

We have to pass the user-account props from the main App component to the Account component. We need to give user-account details to Account in order to render the active account of users. This is where mocking comes in handy, enabling us to test our components with fake data.

Let’s create a mock for the user props:

const user = {
name: “Adeneye David”,
email: “david@gmail.com”,
username: “Dave”,
};

We have created a manual mock function in our test file and wrapped it around the components. Let’s say we are testing a large database of users. Accessing the database directly from our test file is not advisable. Instead, we create a mock function, which enables us to use fake data to test our component.

describe(“”, () => {
it(“accepts user account props”, () => {
const wrapper = mount(<Account user={user} />);
expect(wrapper.props().user).toEqual(user);
});
it(“contains users account email”, () => {
const wrapper = mount(<Account user={user} />);
const value = wrapper.find(“p”).text();
expect(value).toEqual(“david@gmail.com”);
});
});

We have two tests above, and we use a describe layer, which takes the component being tested. By specifying the props and values that we expect to be passed by the test, we are able to proceed.

In the first test, we check whether the props that we passed to the mounted component equal the mock props that we created above.

For the second test, we pass the user props to the mounted Account component. Then, we check whether we can find the <p> element that corresponds to what we have in the Account component. When we run the test suite, you’ll see that the test runs successfully.

We can also test the state of our component. Let’s check whether the state of the error message is equal to null:

it(“renders correctly with no error message”, () => {
const wrapper = mount();
expect(wrapper.state(“error”)).toEqual(null);
});

In this test, we check whether the state of our component error is equal to null, using a toEqual() matcher. If there is an error message in our app, the test will fail when run.

In the next section, we will go through how to test React components with snapshot testing, another amazing technique.

Snapshot Testing

Snapshot testing captures the code of a component at a moment in time, in order to compare it to a reference snapshot file stored alongside the test. It is used to keep track of changes in an app’s UI.

The actual code representation of a snapshot is a JSON file, and this JSON contains a record of what the component looked like when the snapshot was made. During a test, Jest compares the contents of this JSON file to the output of the component during the test. If they match, the test passes; if they don’t, the test fails.

To convert an Enzyme wrapper to a format that is compatible with Jest snapshot testing, we have to install enzyme-to-json:

npm install –save-dev enzyme-to-json

Let’s create our snapshot test. When we run it the first time, the snapshot of that component’s code will be composed and saved in a new __snapshots__ folder in the src directory.

it(“renders correctly”, () => {
const tree = shallow(<App />);
expect(toJson(tree)).toMatchSnapshot();
});

When the test above runs successfully, the current UI component will be compared to the existing one.

Now, let’s run the test:

npm run test

When the test suite runs, a new snapshot will be generated and saved to the __snapshots__ folder. When we run a test subsequently, Jest will check whether the components match the snapshot.

As explained in the previous section, that shallow method from the Enzyme package is used to render a single component and nothing else. It doesn’t render child components. Rather, it gives us a nice way to isolate code and get better information when debugging. Another method, named mount, is used to render the full DOM, including the child components of the parent component, in which we are running the tests.

We can also update our snapshot, Let’s make some changes to our component in order to make our test fail, which will happen because the component no longer corresponds to what we have in the snapshot file. To do this, let’s change the <h3> tag in our component from <h3> Loading…</h3> to <h3>Fetching Users…</h3>. When the test runs, this what we will get in the terminal:

FAIL src/App.test.js (30.696s)
× renders correctly (44ms)

● renders correctly

expect(received).toMatchSnapshot()
Snapshot name: `renders correctly
1

– Snapshot
+ Received

Display Active Users Account Details

– Loading…
+ Fetching Users…

7 | it(“renders correctly”, ()
=> {
8 | const wrapper = shallow();
> 9 | expect(toJson(wrapper)).toMatchSnapshot();
| ^ 10 | });
11 |
12 | /* it(“renders without crashing”, () => {

at Object. (src/App.test.js:9:27)

› 1 snapshot failed.
Snapshot Summary
› 1 snapshot failed from 1 test suite. Inspect your code changes or press `u` to update them.

Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 1 failed, 1 total
Time: 92.274s
Ran all test suites related to changed files.

Watch Usage: Press w to show more.

If we want our test to pass, we would either change the test to its previous state or update the snapshot file. In the command line, Jest provides instruction on how to update the snapshot. First, press w in the command line to show more, and then press u to update the snapshot.

› Press u to update failing snapshots.

When we press u to update the snapshot, the test will pass.

Conclusion

I hope you’ve enjoyed working through this tutorial. We’ve learned some Jest testing techniques using the Enzyme testing library. I’ve also introduced you to the process of running a test, testing React components, mocking, and snapshot testing. If you have any questions, you can leave them in the comments section below, and I’ll be happy to answer every one and work through any issues with you.

Resources And Further Reading

Jest documentation
Enzyme documentation
“How to Test React Components: The Complete Guide”, Mohammad Iqbal, freeCodeCamp
“Testing React With Jest and Enzyme”, Dominic Fraser, CodeClan

Smashing Editorial
(ks, ra, il, al)

How To Add reCAPTCHA v3 to PHP Form and Submit Using Ajax

Original Source: http://feedproxy.google.com/~r/1stwebdesigner/~3/FUxS-fvMeuY/

In this tutorial, we will add Google reCAPTCHA v3 to a PHP form and submit it without leaving the page, using Ajax. If you have had a contact form or any such form on your website, you know how annoying it is to receive spam messages from bots. Google reCAPTCHA protects you from spam and other automated abuse. To follow along this tutorial, you need to have some basic knowledge of HTML, jQuery and PHP.

Millions of Fonts, Themes, Graphics: Starting at ONLY $16.50 per Month

Web Fonts

Web Fonts
8,000+ Fonts

WordPress Themes

WordPress Themes
1,200+ Themes

Graphic Assets

Graphic Assets
32,000+ Graphics

DOWNLOAD NOW
Envato Elements

Why Google reCAPTCHA v3?

We have all had the frustrating experience of trying to quickly submit some information through a form only to be faced by a Captcha challenge in the end. We’ve had to type in random characters and wondered, “Is that two Vs or a W?”, “Should I add that space or not?”.

Google Recaptcha

And then we’ve had to select all the images that have zebra crossing or bridges to prove that we are humans. Thankfully, these days, a lot of websites have added Google reCAPTCHA v2 which just displays a checkbox – “I’m not a Robot”.

Google reCAPTCHA v2

However, in 2018, Google released the next version – reCAPTCHA v3 which doesn’t need any user interaction at all. It works behind the scenes observing the user’s behavior. This version provides us (developers) with a score that indicates how suspicious an interaction is. We could use that score and prevent spam. Read how it works at Google’s official webmaster blog.

Now let’s learn how to add this to a simple form.

Register reCAPTCHA v3 keys

You need to first register your website and get the keys here –  https://www.google.com/recaptcha/admin/create. Add a label, select reCAPTCHA v3, type your domain name(s) and submit.

Google reCAPTCHA v3

This will generate a “site key” and a “secret key”. Copy both and keep them safe. We will need them soon.

HTML Form

Let’s take a simple contact form with Full name, Email and Message fields

Contact Form without Google reCAPTCHA

The HTML

For the sake of simplicity of this tutorial, only the HTML code is displayed below. For CSS used in the above screenshot, download the full source code at the end of this tutorial.

<form id="contact-form" method="post">
<p class="label">Full Name *</p>
<input type="text" name="name" placeholder="Full Name" required>
<p class="label">Email *</p>
<input type="email" name="email" placeholder="Email" required>
<p class="label">Message *</p>
<textarea name="message" rows="6" placeholder="Type your message here" required></textarea>
<!– A hidden div “alert” below to display the message received from server once form is submitted–>
<div id="alert"></div>
<button id="submit-button" type="submit">Send Message</button>
</form>

Ajax Form Submission

Let’s work on the form submission using Ajax before we add the reCAPTCHA, for which we need the jQuery library. Load it using a CDN. Paste this line before the closing body tag in your HTML.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

 

We need to make the Ajax request on form submission.

<script>
$(‘#contact-form’).submit(function(event) {
event.preventDefault(); // Prevent direct form submission
$(‘#alert’).text(‘Processing…’).fadeIn(0); // Display "Processing…" to let the user know that the form is being submitted
$.ajax({
url: ‘contact.php’,
type: ‘post’,
data: $(‘#contact-form’).serialize(),
dataType: ‘json’,
success: function( _response ){
// The Ajax request is a success. _response is a JSON object
var error = _response.error;
var success = _response.success;
if(error != "") {
// In case of error, display it to user
$(‘#alert’).html(error);
}
else {
// In case of success, display it to user and remove the submit button
$(‘#alert’).html(success);
$(‘#submit-button’).remove();
}
},
error: function(jqXhr, json, errorThrown){
// In case of Ajax error too, display the result for demo purpose
var error = jqXhr.responseText;
$(‘#alert’).html(error);
}
});
});
</script>

 

With this code, if you hit “Submit”, you will get a 404 error displayed because contact.php doesn’t exist yet. Let’s do that next.

11,000+
Icons

20,000+
Illustrations

Envato Elements

DOWNLOAD NOW

14,000+
UI & UX Kits

16,000+
Web Templates

PHP

Create contact.php. On the server side, we need to validate the data received and send a JSON response. We will integrate reCAPTCHA in a while.

<?php

// Server side validation
function isValid() {
// This is the most basic validation for demo purposes. Replace this with your own server side validation
if($_POST[‘name’] != "" && $_POST[’email’] != "" && $_POST[‘message’] != "") {
return true;
} else {
return false;
}
}

$error_output = ”;
$success_output = ”;

if(isValid()) {
$success_output = "Your message sent successfully";
} else {
// Server side validation failed
$error_output = "Please fill all the required fields";
}

$output = array(
‘error’ => $error_output,
‘success’ => $success_output
);

// Output needs to be in JSON format
echo json_encode($output);

?>

 

Perfect! We have the complete flow of form submission using Ajax. Now it’s time to integrate reCAPTCHA v3 and you will see how simple it really is, if you carefully follow along.

Client Side Integration

First step is to load the JavaScript API with your sitekey. Paste this below your jQuery CDN link.

<script async src="https://www.google.com/recaptcha/api.js?render=YOUR_SITE_KEY_HERE"></script>

IMPORTANT: Replace YOUR_SITE_KEY_HERE with the site key that you copied earlier.

If you look at the reCAPTCHA v3 docs, we need to call the grecaptcha.execute on each action we wish to protect. In our case, it is the form submission. This call generates a token, which needs to be sent along with our form data to be verified on the server side. Best way to do that is to include a hidden input field in our form like this and dynamically assign the token value to this field:

<input type="hidden" name="recaptcha_response" id="recaptchaResponse">

 

Call this below function just outside of the Ajax request and populate the hidden input field with token value. This will automatically include the token value along with other form data when the Ajax request is made.

grecaptcha.ready(function () {
grecaptcha.execute(‘YOUR_SITE_KEY_HERE’, { action: ‘contact’ }).then(function (token) {
var recaptchaResponse = document.getElementById(‘recaptchaResponse’);
recaptchaResponse.value = token;
// Make the Ajax call here
});
});

IMPORTANT: Replace YOUR_SITE_KEY_HERE with the site key that you copied earlier.

The ‘action’ value is specific to this action of contact form submission. Different actions help you analyse data all over your website when you add reCAPTCHA in multiple places.

NOTE: reCAPTCHA tokens expire every two minutes. Which is why, we need to generate this token only after the user clicks on the submit button and just before we make the Ajax request.

This completes client side integration.

Server Side Integration

Once we validate the data (Name, Email and Message) on the server-side, we need to fetch the score from Google to verify if it’s a human interaction or not. Inside the if(isvalid()){ } block, add the below code to make the API request to get the score.

// Build POST request to get the reCAPTCHA v3 score from Google
$recaptcha_url = ‘https://www.google.com/recaptcha/api/siteverify’;
$recaptcha_secret = ‘YOUR_SECRET_KEY_HERE’; // Insert your secret key here
$recaptcha_response = $_POST[‘recaptcha_response’];

// Make the POST request
$recaptcha = file_get_contents($recaptcha_url . ‘?secret=’ . $recaptcha_secret . ‘&response=’ . $recaptcha_response);

IMPORTANT: Replace YOUR_SECRET_KEY_HERE with the secret key that you copied earlier. Secret key is for server-side only.

The response received is a JSON object.

{
"success": true|false, // whether this request was a valid reCAPTCHA token for your site
"score": number // the score for this request (0.0 – 1.0)
"action": string // the action name for this request (important to verify)
"challenge_ts": timestamp, // timestamp of the challenge load (ISO format yyyy-MM-dd’T’HH:mm:ssZZ)
"hostname": string, // the hostname of the site where the reCAPTCHA was solved
"error-codes": […] // optional
}

 

Let’s decode the JSON object $recaptcha and check for success, score and action. Score varies from 0.0 to 1.0. By default, you can use a threshold of 0.5.

$recaptcha = json_decode($recaptcha);
// Take action based on the score returned
if ($recaptcha->success == true && $recaptcha->score >= 0.5 && $recaptcha->action == ‘contact’) {
// This is a human. Insert the message into database OR send a mail
$success_output = "Your message sent successfully";
} else {
// Score less than 0.5 indicates suspicious activity. Return an error
$error_output = "Something went wrong. Please try again later";
}

 

You’re all set! Hit that Submit button, and if you integrated everything correctly, you should see a response that your message was sent successfully.

success message

Bonus tip:

Once you added the javascript API, you might have noticed an annoying reCAPTCHA badge at the bottom right corner of your page that looks like this.

Google reCAPTCHA badge

This might not go well with your website design. Guess what? This FAQ here says that you are allowed to hide this badge provided you include the following text in the user flow

This site is protected by reCAPTCHA and the Google
<a href="https://policies.google.com/privacy">Privacy Policy</a> and
<a href="https://policies.google.com/terms">Terms of Service</a> apply.

 

So add this within a p element below your “Submit” button.

reCAPTCHA message

Now, to actually hide the badge, just add this into your CSS.

.grecaptcha-badge {
visibility: hidden;
}

 

Congratulations! You have successfully set up Google reCAPTCHA v3 into your form. Now you will receive messages only from humans – without them having to face a Captcha challenge AND without leaving the page.

Download full source code here.

 

DOWNLOAD SOURCE CODE