Step 1: Set up @wordpress/env
1.1 – Install the @wordpress/env package
npm install @wordpress/env --save-dev
Adding @wordpress/env as a dev dependency in your project ensures a consistent version and functionality is used across contributors.
1.2 – Configure .wp-env.json
Add a new file named .wp-env.json to the root of your project, with a basic configuration such as:
{
"core": "WordPress/WordPress",
"plugins": [
"."
],
"themes": [],
}
See the documentation for additional configuration options.
1.3 – Start it up!
npm run wp-scripts start
The initial startup will create the local Docker container where your environment runs.
Step #2: Scaffolding Tests
WP CLI provides a command to automatically set up tests in your project. The basic command looks like this:
wp scaffold plugin-tests
However, this must be run inside the local container. This can be done with the following, where “my-example-plugin” can be replaced with your plugin’s slug:
npm run wp-env run cli --env-cwd=wp-content/plugins/my-example-plugin wp scaffold plugin-tests my-example-plugin
Step #3: Install More Stuff
The scaffolding step above will have inserted a bin/install-wp-tests.sh script, which we should run:
npm run wp-env run cli --env-cwd=wp-content/plugins/my-example-plugin bash bin/install-wp-tests.sh wordpress_test root password mysql
Step #4: Configure PHPUnit
4.1 – Add phpunit.xml
The scaffolding step will also have added a phpunit.xml.dist file to the root of your project.
Create a new file name phpunit.xml and copy the contents of the .dist file into it.
4.2 – Require @yoast/phpunit-polyfills
composer required @yoast/phpunit-polyfills@1.0.1
Step #5: Run The Tests
You can now run your project’s tests via:
npm run wp-env run cli --env-cwd=wp-content/plugins/my-example-plugin vendor/bin/phpunit
Hooray!
Leave a Reply