I have a little problem when I want to test an array in my unit test.
I want to test both structure and type of keys, but I don't know how to process it (I tried, I promise!).
Here is the json input:
{
"success": true,
"data": [
{
"id": 1,
"domains_id": 1,
"sub": "",
"type": "",
"ip_or_fqdn": "",
"created_at": "2022-05-14T08:30:18.000000Z",
"updated_at": "2022-05-14T08:30:18.000000Z"
}
],
"message": "Domain retrieved successfully."
}
And there is, for the moment, the test:
it('fetch zone entries [GET] with json response and check response type', function () {
TestCase::initDatabase();
Passport::actingAs(
User::factory()->make()
);
$response = $this->withHeaders([
'Accept' => 'application/json'
])
->json('GET', '/api/zone')
->assertStatus(200)
->assertJson(function (AssertableJson $json) {
$json->has('success')
->whereType('success', 'boolean')
->has('data')
->whereType('data', 'array')
->has('message')
->whereType('message', 'string');
});
TestCase::resetDatabase();
});
I want to test the "data" array keys/values with this process and, of course, in this Closure; but is it possible?
CodePudding user response:
You may use dot notation, for instance
->assertJson(fn (AssertableJson $json) =>
$json->has('data.id')
->where('data.id', 1)
->missing('data.x')
);
CodePudding user response:
Finally, with @ajthinking tips, here is the final test and it works, thank you very much!
it('fetch zone entries [GET] with json response and check response type', function () {
TestCase::initDatabase();
Passport::actingAs(
User::factory()->make()
);
$response = $this->withHeaders([
'Accept' => 'application/json'
])
->json('GET', '/api/zone')
->assertStatus(200)
->assertJson(function (AssertableJson $json) {
$json->has('success')
->whereType('success', 'boolean')
->has('data')
->whereType('data', 'array')
->has('data.0')
->has('data.0')
->has('data.0.id')
->has('data.0.sub')
->has('data.0.type')
->has('data.0.ip_or_fqdn')
->has('data.0.created_at')
->has('data.0.updated_at')
->whereType('data.0.id', 'integer')
->whereType('data.0.sub', 'string')
->whereType('data.0.type', 'string')
->whereType('data.0.ip_or_fqdn', 'string')
->whereType('data.0.created_at', 'string')
->whereType('data.0.updated_at', 'string')
->has('message')
->whereType('message', 'string');
});
TestCase::resetDatabase();
});