2
votes

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...

2
It may be returning JSON, what the error is telling you though is you are passing a string into the seeJson() function when it only takes arrays. - user1669496
It seems like the data is already formatted in a valid JSON format though... What is the best practice for changing the JSON formatted string into an array in this case? - BakerStreetSystems
I'm not familiar with this function but I'll write up an answer to hopefully explain better. - user1669496

2 Answers

4
votes

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.

1
votes

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']);
    }
}