jgravois's avatar

Test results in Array (...) does not match expected type "string".

I am working on a report that shows a rolling 12-month span.

I started with a test but got hit with Array (...) does not match expected type "string".

/** @test */
    public function can_create_a_12_month_rolling_array () {
        $dt = Carbon::today();
        $reporter[] = [
            'name' => $dt->format('F Y')
        ];

        for($i=1; $i<13; $i++) {
            $reporter[] = [
                'name' => $dt->subMonth()->format('F Y')
            ];
        } // end for

        //dd($reporter);

        $this->assertEquals(Carbon::today()->format('F Y'), collect($reporter)->first->name);

        $this->assertEquals(Carbon::today()->subYear()->format('F Y'), collect($reporter)->last->name);
    } // end test

This is the results of dd($reporter) which is correct.

array:13 [
  0 => array:1 [
    "name" => "April 2020"
  ]
  1 => array:1 [
    "name" => "March 2020"
  ]
  2 => array:1 [
    "name" => "February 2020"
  ]
  3 => array:1 [
    "name" => "January 2020"
  ]
  4 => array:1 [
    "name" => "December 2019"
  ]
  5 => array:1 [
    "name" => "November 2019"
  ]
  6 => array:1 [
    "name" => "October 2019"
  ]
  7 => array:1 [
    "name" => "September 2019"
  ]
  8 => array:1 [
    "name" => "August 2019"
  ]
  9 => array:1 [
    "name" => "July 2019"
  ]
  10 => array:1 [
    "name" => "June 2019"
  ]
  11 => array:1 [
    "name" => "May 2019"
  ]
  12 => array:1 [
    "name" => "April 2019"
  ]
]

Since the dump shows the results are arrays, I tried this

$this->assertEquals(Carbon::today()->format('F Y'), collect($reporter)->first['name']);

$this->assertEquals(Carbon::today()->subYear()->format('F Y'), collect($reporter)->last['name']);

but that gives me Cannot use object of type Illuminate\Support\HigherOrderCollectionProxy as array

0 likes
1 reply
bobbybouwmann's avatar

That is because collect($reporter)->first['name']) doesn't return a string right now. I believe it should be this

$this->assertEquals(Carbon::today()->format('F Y'), collect($reporter)->first()['name']);

$this->assertEquals(Carbon::today()->subYear()->format('F Y'), collect($reporter)->last()['name']);

Please or to participate in this conversation.