How can you unit test your plugin or theme without WordPress or other dependencies? You simulate the dependencies. My favorite tool to redefine and mock functions is Brain Monkey. In this hands-on testing lab, you will write unit tests using Brain Monkey.
Labs
Labs are hands-on coding projects that you build along with Tonya as she explains the code, concepts, and thought processes behind it. You can use the labs to further your code knowledge or to use right in your projects. Each lab ties into the Docx to ensure you have the information you need.
Each lab is designed to further your understanding and mastery of code. You learn more about how to think about its construction, quality, maintainability, programmatic and logical thought, and problem-solving. While you may be building a specific thing, Tonya presents the why of it to make it adaptable far beyond that specific implementation, thereby giving you the means to make it your own, in any context.
Unit Testing with Brain Monkey
`with()` – Code Challenge
Let’s walk through the code challenge I gave to you in the last episode.
More with `with()`
Let’s build another test to learn more about using with()
`with()`
We can test that the arguments the mocked function receives are what we expect by using the with() method. Mockery, which is baked into Brain Monkey, inspects the received arguments and then tests each one against what you’ve defined it should receive. This feature allows us to ensure our code is properly doing its work and sending the right set of data to the function we are mocking. Here, let me show you.
`stubs()`
Stubs give you a way to redefine multiple functions by passing an array to Brain Monkey. This toolset is handy for things such as WordPress escaping and internationalization functions, as we can bulk define these functions in your Test Case. Here is an example of how we do it with the Beans framework.
`when()` – Code Challenge
Time for a code challenge to make sure you now understand how when() works and how to use each of its different task options. Let’s write 4 different when() definitions for the WordPress function esc_html_e(). Then we’ll discuss how to select the best option as well as how to keep your code DRY.
Lab Setup
In this episode, I’ll quickly go over what you will be doing in this lab. Then I’ll walk you through how to setup your environment for the lab. For this, you will want to: Setup a local website on your Mac or Windows machine. Navigate into your themes directory. Clone this repository, which gives you the theme we’ll use in the Testing Series. Navigate into the new theme. Install the Composer dependencies. Run composer test-unit to make sure everything works. You will need your local machine setup and ready to go. If you need help, go to either of these […]