Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

255
Visualizações
Laravel 5.4 testing route protected by $request->ajax(), how to make test ajax request?

I am trying to test a route that does something different in the controller whether or not the request is ajax or not.

public function someAction(Request $request)
{
    if($request->ajax()){
        // do something for ajax request
        return response()->json(['message'=>'Request is ajax']);
    }else{
        // do something else for normal requests
        return response()->json(['message'=>'Not ajax']);
    }
}

My test:

    public function testAjaxRoute()
{
    $url = '/the-route-to-controller-action';
    $response = $this->json('GET', $url);
    dd($response->dump());
}

When I run the test and just dump the response I get back 'Not ajax' - which makes sense I guess cause $this->json() is just expecting back a json response, not necessarily making an ajax request. But how can I correctly test this? I have been commenting the...

// if($request->ajax(){
    ...need to test this code
// }else{
    // ...
// }

every time I need to run the test on that portion of code. I'm looking for how to make an ajax request in my test case I guess...

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

In Laravel 5.4 tests this->post() and this->get() methods accept headers as the third parameter. Set HTTP_X-Requested-With to XMLHttpRequest

$this->post($url, $data, array('HTTP_X-Requested-With' => 'XMLHttpRequest'));

I added two methods to tests/TestCase.php to make easier.

<?php

namespace Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;

    /**
     * Make ajax POST request
     */
    protected function ajaxPost($uri, array $data = [])
    {
        return $this->post($uri, $data, array('HTTP_X-Requested-With' => 'XMLHttpRequest'));
    }

    /**
     * Make ajax GET request
     */
    protected function ajaxGet($uri, array $data = [])
    {
        return $this->get($uri, array('HTTP_X-Requested-With' => 'XMLHttpRequest'));
    }
}

Then from within any test, let's say tests/Feature/HomePageTest.php, I can just do:

public function testAjaxRoute()
{
  $url = '/ajax-route';
  $response = $this->ajaxGet($url)
        ->assertSuccessful()
        ->assertJson([
            'error' => FALSE,
            'message' => 'Some data'
        ]); 
}
over 4 years ago · Santiago Trujillo Relatório

0

Try $response = \Request::create($url, 'GET', ["X-Requested-With" => "XMLHttpRequest"])->json();

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda