david001's avatar

unit testing: send parameters to endpoint

Hi, my question is how to send parameter to my endpoint.

route: Route::get('users/plan','DashboardController@filterPlan')->name('users.filter');

test


public function test_upgrade()
    {
       
        $billingChange3 = factory(Plan::class)->create([
            'user_id' => 1,
            'previous_price' => 50,
            'current_price' => 100,
        ]);
       
        $url = route(
            'users.filters'
        );
        $response = $this->actingAs($this->admin)->getJson($url,['search'=>'upgrade']);
        $response->assertStatus(200);
        //till here correct 
        //but here it should return 2 since I have upgrade count 2  as correct it gives error
my api response is wrapped within data, so i have used data below
        $response->assertJsonCount(2,'data');
    }
my seach keyword can be any thing such as ```upgrade,downgrade``` etc. 
upgrade is when ```current_price>previous_price``` and I have logic for that in controller 

My vue dev tool shows url as below:
    first:"https://localhost:800/users/plan?filter=upgrade&page=1"
In test I have passed params as``` getJson($url,['search'=>'upgrade']```
Is that the correct way to pass paramters?
0 likes
8 replies
wingly's avatar
wingly
Best Answer
Level 29

Use the route helper:

        $response = $this->actingAs($this->admin)->getJson(route('users.filter', ['search'=>'upgrade']));
tykus's avatar

You cannot pass query parameteres with getJson - check the method signature out. Use the json method instead:

$response = $this->actingAs($this->admin)->json('GET', route('users.filters'), ['search'=>'upgrade']);
1 like
tykus's avatar

getJsonis a convenience method that delegates to json; '

    /**
     * Visit the given URI with a GET request, expecting a JSON response.
     *
     * @param  string  $uri
     * @param  array  $headers
     * @return \Illuminate\Testing\TestResponse
     */
    public function getJson($uri, array $headers = [])
    {
        return $this->json('GET', $uri, [], $headers);
    }

As you can see, it lacks for an argument where you can set query parameters, so you either (i) use json and set an array or (ii) write the URI with a query string, e.g. $this->getJson('users/plan?search=upgrade')

tykus's avatar

We don't know your implementation 🤷‍♂️

I have 3 insertion

Or, where your test makes three insertions?

tykus's avatar

Yes, but how does you test come to have more than one record?

Please or to participate in this conversation.