2
votes

I am writing Feature Tests for my Laravel Application, where I perform some requests to my service.

While trying to test my API, all GET requests work fine, but all POST requests return this response:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="refresh" content="0;url='http://localhost'" />

        <title>Redirecting to http://localhost</title>
    </head>
    <body>

My test code looks like this:

$this->post('api/my/route')->dump();

and my api routes look like this:

Route::prefix('my')->group(function() {
    Route::post('/route', function() {
        return 'ok';
    });

Are there any middleware etc. I might need to change/deactivate before creating a request like this?

These requests work fine when using the web.php routes

2
which response are you getting after request? can u show response?Ariful Islam
Did you tried with $this->postJson('api/my/route')?mare96
@mare96 Thank you! postJson seems to do the trick, even though I am not returning JSON from my routetopiji
@topiji You are welcome. I added an answer to be more precise.mare96
@topiji Did you know (I certainly didn't) that for language specification in code blocks you have to do a lowercase ```html (not ```HTML)?Thomas F

2 Answers

2
votes

As @Deepesh Thapa mentioned, you should return JSON.

And in your test, you should add postJson like this:

$this->postJson('api/my/route')

Go through the docs.

Good luck!

1
votes

You will need to return a json response. The json method will automatically set the Content-Type header to application/json, as well as convert the given array to JSON using the json_encode PHP function:

So you should indeed return data as below.

Route::prefix('my')->group(function() {
    Route::post('/route', function() {
        return response()->json(['message'=>'ok']);
    });