JasonJensenDev
JasonJensenDev

Reputation: 2407

Laravel 5.1 PHPUnit Tests for API using JSON

I just started working with Unit testing in Laravel 5.1 to test an API I'm building, and I can get PHPUnit to work fine with the ExampleTest.php, but when I create my own test, it fails every time.

Here is the response for my API endpoint v1/conversations:

{
  "data": [
    {
      "id": 1,
      "created_at": "2015-07-05",
      "updated_at": "2015-07-07"
    },
    {
      "id": 2,
      "created_at": "2015-07-06",
      "updated_at": "2015-07-08"
    }
  ]
}

Here is my ConversationsTest.php:

<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ConversationsTest extends TestCase
{

    public function test_list_conversations()
    {
        $this->get('v1/conversations')->seeJson('data');
    }
}

But when I got to run my test, I get the following:

There was 1 error:

1) ConversationsTest::test_list_conversations
ErrorException: Argument 1 passed to Illuminate\Foundation\Testing\TestCase::seeJson() must be of the type array, string given

Isn't my API returning valid JSON data? Why can't Laravel's seeJson method interpret the response? I've tried to follow the Laravel 5.1 Testing APIs documentation, but I'm clearly missing something...

Upvotes: 2

Views: 3765

Answers (2)

Eduardo Cruz
Eduardo Cruz

Reputation: 617

Try this

<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ConversationsTest extends TestCase
{

    public function test_list_conversations()
    {
        $this->get('v1/conversations')->seeJson(['data']);
    }
}

Upvotes: 1

user1669496
user1669496

Reputation: 33048

The data returned by your endpoint is fine and should not be modified. The error is simply telling you that you are passing a string into the function seeJson('data');

According to this here, https://github.com/laracasts/Integrated/wiki/Testing-APIs, you should be able to use it like so just to verify that some JSON is being returned...

$this->get('v1/conversations')->seeJson();

You can also pass in an array to this function to see if a certain part of the data exists...

$this->get('v1/conversations')->seeJson([
    'data' => 'some data',
]);

Though that will likely fail unless you pass in the entire array which is also being returned by your endpoint.

The only thing you can not do is pass in a string to this function as it wouldn't know what to do with a string.

Upvotes: 4

Related Questions