Tests for REST API are even more important because you never know how the API may respond to various environments or situations. If you haven’t set up PHPUnit tests for your WordPress plugin yet, I’d recommend checking out the guide Plugin Integration Tests by WordPress. If you face any issues while setting up, check out common issues while setting up PHP Unit tests for the WordPress plugin.


Registering CPT.

Let’s begin with registering a custom post type with REST API enabled.

add_action( 'init', 'register_items_cpt' );
function register_items_cpt() {
          $args = apply_filters(
              'items_post_type_args',
              [
                'labels' => 'Items',
                'description' => 'Custom Post Type Description',
                'supports' => [ 'title' ],
                'show_in_rest' => true,
              ]
          );

        register_post_type('items', $args);
}

For the list of arguments that can be passed, see register_post_type documentation. The important argument to note is “show_in_rest” which should be true (default false) to register the CPT endpoint.

Now if you enter the URL like https://localhost/wordpress/wp/v2/items, you’ll see the list of items.


Writing Tests.

Now that we’ve registered an endpoint for our CPT, let’s write a test. So, in the plugin’s test directory, create a file so that the structure would be: your-plugin/tests/test-items-rest-api.php

The class should extend WP_UnitTestCase. The class should be :

class Test_Items_Rest_API extends WP_UnitTestCase {

     /**
      * Holds the WP REST Server object
      *
      * @var WP_REST_Server
      */
     private $server;

     /**
      * Holds post id.
      *
      * @var int
      */
     private $postId;
}

The $server and $postId are properties for WP REST Server and our test Post ID.

Let’s create member functions. There are three minimal functions, but you can add any that are required.

the setUp() method which call the parent class’s setUp()

In this method, we initiate the REST API and the call to ‘rest_api_init’ to register our custom endpoint for the test suite. We’ve also created a new post to perform our tests.


    /**
     * Create a item for our test and initiate REST API.
     */
    public function setUp()
    {

        parent::setUp();

        // Initiating the REST API.
        global $wp_rest_server;
        $this->server = $wp_rest_server = new WP_REST_Server();
        do_action('rest_api_init');

        $this->postId = $this->factory->post->create([
            'post_title' => 'Chair',
            'post_status' => 'publish',
            'post_type' => 'chair',
        ]);
    }
the tearDown() method.

This is used to clean up all the things we do after the tests. Here we’ve set the $wp_rest_server to null like before and deleted the created post.


    /**
      * Delete the item after the test.
      */
    public function tearDown()
    {

         parent::tearDown();

         global $wp_rest_server;
         $wp_rest_server = null;

         wp_delete_post($this->postId);
    }
Our custom method. let’s name testItemsEndpoint()

The actual test is performed in this method. We’re performing two tests.

  • Checking if status of the response is 200, which indicates the successful response.
  • Checking if the title of our post is Chair, which we’ve created during setUp().
     /**
      * Test the endpoint for Person CPT.
      *
      * @return void.
      */
    public function testItemsEndpoint()
    {

        $request = new WP_REST_Request('GET', '/wp/v2/items/' . $this->postId);
        $response = $this->server->dispatch($request);
        $data = $response->get_data();

        $this->assertEquals(200, $response->get_status());
        $this->assertEquals('Chair', $data[0]['title']['rendered]);
    }

Now enter phpunit and enjoy developing! 🙂

Writing PHPUnit test for REST API & Custom Post Types in WordPress
Tagged on:     

Sanjeev Aryal

Don't bury your thoughts, put your vision into reality ~ Bob Marley.

Leave a Reply

Your email address will not be published. Required fields are marked *

× WhatsApp