Laravel 测试:如果需要检查多个级别,assertJsonFragment 会失败

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

这是回复:

[  
  {  
    "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
  }
]

我想断言以下片段是响应的一部分:

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

有什么方法可以断言 translate 数组至少包含一个键为 nl_NL 的元素,并且 validate 包含一个键为 [=17= 的元素]?

$response->assertSuccessful()->assertJsonFragment([
    'translate' => [['key' => 'nl_NL']],
    'validate'  => [['key' => 'it_IT']
]);

assertJsonFragment()不可能做到这一点。

你可以这样做:

$this->assertTrue(
    collect($response->decodeResponseJson('0.data.locales.translate'))
        ->pluck('key')->contains('nl_NL')
);