Testing JavaScript: The WordPress Way

Today I am presenting at the second JavaScript For WordPress conference. My talk is “JavaScript Testing In And Around WordPress.” It’s a two part talk, first about testing React apps. The second part gives applies those topics to WordPress plugins that add blocks to the WordPress block-based editor.

I’m really geeked about this talk. Testing JavaScript apps is also I find a lot of fun. I also think that this next phase in WordPress development — a move to React-powered UIs that are often decoupled from WordPress is great — but requires a serious commitment to automated testing or we will not be able to meet the needs of people visiting our sites or those building them.

A key benefit of developing blocks loosely coupled to WordPress is you can reuse the components anywhere. This is great – you spend less time developing duplicate functionality, and a more consistent user experience. The downside is if any component becomes buggy or defective it affects every client consuming it. That’s a big risk and if you’re not developing the component in every single context it’s used, then the bug or defect may not be obvious.

– Me, in a recent guest post for Pantheon that I don’t want to just repeat the same arguments from in this post. But, TL;DR – resuse is good, as long as the component works everywhere, which we can prove, with tests.

Using WordPress Scripts For WordPress Block Development

I want to highlight one part of my talk, which covers the WordPress Scripts package – @wordpress/scripts. This is a zero-config build and testing tool for WordPress development. It works on top of Jest, Babel, webpack and other tools you need for modern JavaScript development.

This is the easiest way to configure Babel and webpack for WordPress development. It’s like create-react-app for WordPress.

How To Add WordPress Scripts To Your Plugins

This is a quick guide, the slides and the README, have way more information.

First, install:

yarn add @wordpress/scripts

Update package.json –

    "scripts": {
        "build": "wp-scripts build",
        "check-engines": "wp-scripts check-engines",
        "check-licenses": "wp-scripts check-licenses",
        "lint:css": "wp-scripts lint-style",
        "lint:js": "wp-scripts lint-js",
        "lint:pkg-json": "wp-scripts lint-pkg-json",
        "start": "wp-scripts start",
        "test:e2e": "wp-scripts test-e2e",
        "test:unit": "wp-scripts test-unit-js"

Then create a Gutenberg block at /src/index.js. You can compile it to build/index.min.js like so:

yarn build

Or do many other things, such as testing. Which I cover a lot in this talk 🙂

You can see a complete example of how this all works in this example code plugin I put on Github for this talk. Also, so I can use it as a template for when I have to make a plugin.

How To Use WordPress e2e Testing Tools

This plugin and the talk cover automated browser testing with the WordPress end to end testing tools. This could have been its own talk. I did want to have a complete example of how to set up the local development environment and configure Jest for these tests.

Slides And Links

JavaScript Testing In And Around WordPress

Example Code

BTW I Used MDX-Deck, It Is Good.

This is an off-topic aside about making the slide deck. Because, Josh.

I normally use Google slides. I’m never happy with how code looks, if its pasted in as text. With a lot of effort, I’ve gotten it to look good with screenshots. That makes the code invisible to users who do not load images and you can’t cut and paste the code from the deck.

Anyway, I started thinking about how I wished I could just write it in markdown. MDX mixes React JSX and markdown. It’s really ideal for writing about code and mdx-deck wraps it up in a slide presentation. Very cool.

Best part is, I wrote it in vsCode. The syntax highlighting and automatic code formatting in vsCode is much better than in Google Slides.

In the future, it would be way better if I used a monorepo to store the example code and the deck in the same repo. Next time:

Two Rules Of JavaScript Async/Await

Ever wanted to write a JavaScript function that makes a HTTP request and then returns the results? Sounds simple, but the “and then” part of that sentence includes a lot of complexity. That is because when you make an HTTP request — it is performed asynchronously. This applies to jQuery AJAx, fetch, Axios, Nodes’s HTTPS module, etc.

I’m not going to cover callbacks and promises. I want to ask you to forget about all that and learn two rules. With those rules, and a modern JavaScript runtime, you can write a function that solves the requirement I gave before in a few, highly readable lines, using async/ await.

I say highly-readable because what I love about async/ await is that you can read the code and get a much easier sense of what is going on. Instead of understanding then/when/catch/error/whatever, you see the request on one line and on the next line you see what is done with it.

In this post, I’m going to give you two basic rules of async/ await and some practical examples of their use. It’s a hard to explain this concept, but the code is short and readable, so you should be comfortable, when you’re done to start experimenting with this new API.

Rule One Of Aysnc/ Await

You Must Use The await Keyword Only In Closure That Is Declared With The async keyword.

Inside of this closure, we may use awaitbecause the async keyword is used when declaring the function.

The await keyword is the real magic of async/ await. Before you can use it –see rule two — you must know rule one. Rule one shows us how to create closure that can use the await keyword. How? We type the async keyword before a function. 

Got that? That’s rule one, you’ll see examples when I explain rule two under the next heading.

Rule Two

Inside Of An async Closure, If Another async Function Is called With The await Keyword, The Next Line Will Not Run Until That Line’s Promise Has Resolved.

In this example, line 7 will not run until the Promise created on line 6 has been resolved or rejected.

In this example, I’m using the fetch API, which creates a promise. That’s all been made invisible by using await. Instead of using a then() callback, I’m just awaiting the result of the function.

Notice that the before I declare the function I used the async keyword. That’s another example of how rule one works. This function says async in front of it, so I can use await inside of it.

You can use this asynchronous function only inside of another asynchronous function. For example:

Inside of an async function, we can await the results of an async function.

For a more complete example, here is a more abstract version of getMostRecentPost() that works with any site and then another function that calls it twice and after awaiting those results, returns both posts.

One async function calling another async function using await.
fetch API

That’s The Whole API! Use It!

In this post, you learned two rules of async/ await and that’s all you need to know to use this powerful new feature of JavaScript. It will make your code simpler in a lot of cases.

Want to learn more? I’ll leave you with a Wes Bos video:

A List Of Developer-Facing Talks About The New WordPress Gutenberg Block Editor

The new WordPress block-based “Gutenberg” editor is coming to WordPress soon. I’ve given a few talks about developing for Gutenberg. In this post I round up three talks, in three categories, that I think can give you a good overview of developing for Gutenberg.

Don’t forget to read the Gutenberg Handbook, which has a ton of documentation about working with and extending the new WordPress editor. These are talks for developers, I published a list of talks for site-builders and WordPress users yesterday.

This list is part of the resources for my React Boston 2018 talk. You can see those slides here.

Design For Gutenberg

Building Blocks

Advanced Topics In Gutenberg

Resources About Gutenberg For Site Builders

Last week I gave a talk called “Introduction To Gutenberg Block Development” at WordCamp Pittsburgh. It was a developer-facing talk about how to build a custom block type for the new WordPress block-based “Gutenberg” editor, coming very soon to WordPress.

You do not need to create your own blocks to use Gutenberg. I had one slide of links in my talk for those who are looking to learn how to use Gutenberg.

For the developer-facing version of this list, please see this post.

The List

A Comprehensive Guide to the New Block Editor

Create A WordPress Site With Lando

For local WordPress and Laravel development, I tend to use a Docker-based solution, most of the time. Depending on the project, I either use Lando or docker-compose. This post is about Lando.

Lando, is no DesktopServer. DesktopServer gives you a simple GUI for creating WordPress sites. Lando has no user interface, you do everything from the command line. That’s good or bad, depending on what you need.

This article explains how I create new sites for local development using Lando. You can see my current .lando file that I use for Caldera Forms development here.

Create The WordPress

Initialize lando in current directory:

lando init --recipe=wordpress

Add a WordPress:

wp core download

That downloaded WordPress core and setup wp config to match Lando’s default variables:

wp config create --dbname=wordpress --dbuser=wordpress --dbpass=wordpress --dbhost=database --skip-check

Add xdebug and MailHog and phpunit

Optional step, but it’s best before going further to add phpunit, MailHog and xdebug. MailHog intercepts all emails coming from the application and provides a webmail-like UI for reading the caught emails.

I love xdebug, I can’t imagine PHP development without it.

In order to run tests “The WordPress Way” you need phpunit installed globally. I disagree with this approach, but Lando makes it pretty simple to do, so fuck it. Here is a .lando.yml file that adds all of these things:

name: formcalderas
recipe: wordpress
  env: dev
  xdebug: true
    - mail.formcalderas.lndo.site
      phpunit/phpunit: '*'
      type: mailhog
        - appserver
      portforward: true

Build Containers And Start the site

lando start

This builds the new site and then shows URLs for the site.

At that point you have a WordPress at the URL listed for “APPSERVER URLS”. Click the https link and then finish installing WordPress through the UI. Alternatively use wp cli.

Chrome will not trust the SSL certificate. I normally just click the “Advanced” option and then tell Chrome to trust it. There is a better way to handle this documented here.

Path Mappings For xdebug In phpStorm

In phpStrom preferences go to Language & Frameworks > PHP > Servers and select the current server. Map the root directory to /app

Use It With Bedrock!

Bedrock, along with the Sage Framework is a great option for WordPress app development. Here is a guide to using Lando with Bedrock.

Also Great For Pantheon!

This article is about setting up local sites for general plugin development. We also use Lando for local development of the Caldera Forms site. CalderaForms.com is hosted on Pantheon. We git commit the Lando config file in the repo for the site. That way we have a shared environment and can pull database and file changes using Lando’s CLI, thanks to their Pantheon integration.

Learn more about Lando + WordPress here.

A Listicle Of Laravel Nova Related Blog Posts

This is my list of all of the useful articles I found while experimenting with the Laravel Nova. I will update it with more links as I go.

Laracon 2018 keynote, announcing Laravel Nova.

Nova Packages

Nova Tutorials

Nova Related Links That Do Not Fit In the Above Categories

Customizing the Nova dashboard theme.

Easy Things

I’ve developed a reputation at my company for declaring tasks “easy” that end up being very difficult or impossible. I deserve it.

This happens for two reasons. One reason is I underestimate the understanding that the person has more experience and knowledge then I think. The other is I don’t take the time to think through how to solve the problem before declaring it easy.

Let’s stick with option one, short post.

Multi-Tasking Is Hard AF

I’m writing this on my way to the office. I take the bus, which is great as it ads 4 extra walks to my day. It’s raining, I don’t have a small umbrella for the umbrella pocket in my bag. I don’t have a light-weight jacket with a hood.

I’m doing better when I first started going to an office — after over 5 years if working from home. I now check the bus schedules before I leave and I’m almost always on time for the bus. I even check the weather — hey I brought a hoodie today 🙂

So I’m New At This…

I’m doing something new, and I’m trying to be kind to myself as I stumble through it. I do wonder if I work too much as a way to avoid doing the things I’m uncomfortable with.

I used moving to Pittsburgh as my excuse to start leaving the house more. It gave me tons of anxiety at first. That anxiety lead to silly mistakes, which made the experience and anxiety worse. It’s easy to stay caught in that feedback loop.

The thing that’s great about my job is I spend a large part of my day writing code. Something I’m good at. Something that gives me a great sense of calm to do.

Always Itterate

Sometimes I catch myself listing steps for household tasks… Clean up after meal, reduce mess : put dishes in sink, rinse dishes, put dishes in dishwater, push in chair, wipe down table…

I’ve taken the first rule — in my mind — of programing to heart. Before you write code, understand the problem and map a solution. 

I know that taking a structured approach to self-improvement is not a revolutionary new approach to life. But being mindful of how I have to approach things that others may think are simple as a complete novice, I think that helps

I don’t think you can find that empathy for beginners by doing the thing you’re good at. I think it comes through struggling through the rest.

The good thing about this theory is it works better if when I make mistakes I don’t go to putting myself down right away and instead be forgiving of my own lack of skill or experience.

Is Guten-Pain Good?

Gutenberg, the new WordPress post editor is coming soon and its a big change. Change makes people scared, that’s natural. Not all of that fear, in my opinion, matches up with the reality of what Gutenberg actually does and does not do. But, its a big change with some very real risks.

What WordCamp Montreal Taught Me

I attended WordCamp Montreal recently. Besides how great the vegan food was in Montreal I had two big takeaways:

First, industry veterans are excited about the possibility of Gutenberg and are also very worried about the transition. I think some of that is people still not understanding that Gutenberg WordPress 5.0 doesn’t change existing content. But also, there are some valid concerns there.

My other big set of takeaways was from a talk by Jer Clarke about Buddhism and WordPress. This was a great talk. It was not heavy on WordPress content but did make light of the how everything including WordPress changes.

It reminded me of how many times I’ve told people something like, “I used to be so stressed about technical debt and not having enough time for everything I want to build and not making enough money. Now, I’ve got technical debt, not enough time and not enough money.” Then they look at me as if I have something else to add, and I don’t. I’m just more at peace with the fact that these things are happening and less attached to worrying about them.

I still break down and cry, but way less often. I also meditate and exercise every day. I think it helps.

What About The Gutes?

Yes, Gutenberg is a big deal. My big concern, as someone whose business is based on WordPress’ huge market share, is that Gutenberg will lead to a shrinking size of the available customers for me.

It might.

Also, Squarespace. Also the rise in Laravel-backed CMS and CMS-like tools like Nova. Also, serverless static site platforms like Netlify are getting more CMS-like features.

I’m a big fan of the scenario where distributed web apps backed by an Etherum-like blockchain.

Some Disappointing Things Will Happen

I’ve been very concerned about what happens when folks, who chose WordPress based on its promise of backwards compatibility, have to chose between paying to fix problems created by Gutenberg and paying for a new site.

A lot of people own websites that they do not maintain. 

I wonder why we in the community are so attached to supporting those who do not expect to have to support their own sites. That’s their free choice, and if they leave WordPress when faced with this responsibility is that such a bad thing?

I Don’t Know Anything

Or maybe everything will go better than we fear. Maybe Gutenberg really is what WordPress needs to stay relevant.

I have no fucking clue. But I do know that, right now using WordPress, without Gutenberg, to create content is painful. Fearing what happens when you update is scary. These are all know threats to the WordPress ecosystem. They are are real and scary.

Things are changing and that’s difficult and scary.

Also, the sky is blue and no one is forcing you to update. Classic editor or staying on 4.x might be the best solution for existing sites.

I don’t know, but I so hope it goes well. I really want to keep going back to WordCamp Montreal every year, the began food is great.

Top 10 Time-Saving Tips For Writing With Gutenberg

One of my current goals is to write five short blog posts a week using Gutenberg, I want to learn this important new feature of WordPress and be a better contributor. In addition, I want to improve my writing practice by practicing more.

I didn’t set out to write most of my content about Gutenberg, but I should not be shocked that’s what happened. After a few days, I had a few concerns about the experience of authoring content in Gutenberg.  I’m used to writing mainly in Google Docs and Google Keep or Twitter. Sometimes in Simple Note and occasionally WordPress.

Turns out that a lot of these concerns I had are being addressed. The solutions are there, but not obvious. Here are a few tips I’ve learned to improve the content writing experience. When I’m writing, not editing, Gutenberg can feel like it is in the way, but there are good features that exist or are being worked on to solve this.

Slash Commands

One thing that bothered me a lot about writing with Gutenberg In my first week of my new Gutenberg challenge was adding a heading block. I found that having to go to block inserter to add the heading really upset my writing flow.

On Twitter, Kevin pointed out that you can use a slash command to bring up the block inserter. 

To insert a heading block, just start typing /heading brings up a mini block inserter. It’s way faster.

Inserting a heading block into the WordPress Gutenberg post  editor using a slash command
Add blocks quickly to the WordPress editor using a slash command

Code Formatting

I’m using Gutenberg on two sites right now: this site and the CalderaWP handbook site. On the handbook site this week I was documenting setting up local development for CalderaForms.com and needed to use code formatting on some words in a sentence.

There is no obvious way to add <code> or <pre> to selected words in paragraph or list block. This made writing those docs a pain, I had to add the HTML in the code editor. Yes there is a code block, but switching blocks upsets my flow and sometimes I want to put code in a sentence.

Cool feature, not easily discovered. I wish I knew how to make that obvious, as its really cool.

Hide The Sidebar

In the top right menu is a gear icon. Click that to close the Gutenberg sidebar when you’re writing. It’s better that way.

Use The Document Outline Tool

Using the document outline in Gutenberg to see that your 10 items listicle only has 4 items. Also, accept that fact and go back to writing code.

The document outline tool —  i in a circle icon on top right — shows you your heading structure for the document. It makes it easier to see bad heading structure and to jump around a large document.

Another thing that is great about this tool is if you’re writing a listicle that promises ten time-saving tips or whatever, you can use it to count your time-saving tips as you go.

Creating Gutenberg Blocks With WP-CLI

If you’ve never created a Gutenberg block before, or just need to make a quick block, wp-cli — the official command line tool for WordPress — can help. The wp scaffold command can create a plugin and add a block to it. Here is an example:

# create a plugin called books
wp scaffold plugin books
# create a block with the name "book" and the title "Book" in the plugin books
wp scaffold block book --title="Book" --plugin=books

This gives you a plugin with one block. Brian Richards’ section of the WordCamp Miami workshop we gave this year is about creating similar blocks, with or without wp-cli and then adding capabilities to them. The example code from that talk and the slides are likely good next steps if you’re just learning Gutenberg block development.

wp scaffold

This Is Super Basic

I’m a big fan of using ES6 and webpack and yarn and JSX…

If you do not know how to use all of those things and you also do not know how to build a Gutenberg block, I recommend picking one concept to learn at a time. Gutenberg can be your way to level up your JavaScript. But start simple.

Make Something!

In preparation for our Gutenberg-powered future, now that the API is pretty stable,  now is a great time to build your first block. If this helped, @ me on Twitter with the Github link to what you built 🙂