WordPress has a long record of unit testing its PHP code. However, writing JavaScript unit tests and integration tests for the code in themes and plugins doesn’t enjoy the same status. Let’s see how to test the JavaScript in our WordPress plugins and themes using Jest.

JavaScript Unit Tests in WordPress

So why write unit tests and integration tests? They’re great ensure that a function, class method, or even a React component, does what they’re supposed to do. It helps detect errors in the code and also helps preserve integrity when changes are later introduced in the code by verifying it’s still working as intended after the update.

WordPress plugins and themes are mostly written in PHP and can use PHPUnit suite for running tests, making assertions, mocking functions and more. The handbook even has a section explaining how to quickly setup unit testing with the WP-CLI.

For JavaScript, there’s a page about running QUnit tests in the Handbook, although it’s more about testing the JavaScript code in WordPress core.

While none of this is standardized for JavaScript in WordPress, we can write great unit tests using the Jest testing suite. In this article we’ll learn how to write JavaScript unit tests for an example plugin that loads 5 posts through the WP REST API using the fetch function from JavaScript and renders them in a certain DOM element in the page.

Benefits of using Jest for JavaScript unit tests in WordPress

In the past, writing JavaScript unit tests involved setting up Mocha to run tests, Chai to make assertions, and Sinon to mock functions and spy on them. While they offer great flexibility, it’s much more complex to work with three packages than one. Jest provides all this in a single package:

  • you can run tests declaring them with describe and it or test
  • you can make assertions with expect and toBetoHaveLength and many more
  • you can mock functions and spy on them, and there are multiple ways to do this

Before moving on

In order to keep this article focused on testing with Jest, there’s additional setup external to the process of testing like Babel or Webpack that won’t be covered here. All this can be found in the WP Jest Tests repo that accompanies this article. To keep things contextual, each section will link to one of the relevant files that we’ll write.

#javascript #wordpress #development #jest #unit testing #programming

Easy JavaScript unit tests in WordPress with Jest
9.00 GEEK