Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Testing: assertJsonFragment fails if multiple levels need to be checked

This is the response:

[  
  {  
    "data":{  
      "locales":{  
        "translate":[  
          {  
            "created_at":"2018-05-28 12:49:53",
            "deleted_at":null,
            "id":1,
            "key":"nl_NL",
            "name":"Netherlands (Nederlands)",
            "updated_at":"2018-05-28 12:49:53"
          }
        ],
        "validate":[  
          {  
            "created_at":"2018-05-28 12:49:53",
            "deleted_at":null,
            "id":2,
            "key":"it_IT",
            "name":"Italian (Italiano)",
            "updated_at":"2018-05-28 12:49:53"
          }
        ]
      }
    },
    "error":false,
    "message":null
  }
]

I want to assert the the following fragments are part of the response:

1) ['translate' => [['key' => 'nl_NL']]]
2) ['validate'  => [['key' => 'it_IT']]]

Is there any way to assert that the translate array contains at least an element with the key of nl_NL and validate contains an element with the key of it_IT?

$response->assertSuccessful()->assertJsonFragment([
    'translate' => [['key' => 'nl_NL']],
    'validate'  => [['key' => 'it_IT']
]);
like image 408
GiamPy Avatar asked May 29 '18 08:05

GiamPy


1 Answers

That's not possible with assertJsonFragment().

You can do something like this:

$this->assertTrue(
    collect($response->decodeResponseJson('0.data.locales.translate'))
        ->pluck('key')->contains('nl_NL')
);
like image 140
Jonas Staudenmeir Avatar answered Oct 09 '22 22:10

Jonas Staudenmeir