Home > Blockchain >  Expected response status code [201, 301, 302, 303, 307, 308] but received 404
Expected response status code [201, 301, 302, 303, 307, 308] but received 404

Time:12-16

Why am I receiving this error? Seems like I am doing everything correctly

Test:

    public function test_user_can_add_product_to_cart()
    {
        $user = User::factory()->create();

        $this->actingAs($user);

        $response = $this->post('addProductToCart', ['quantity' => 4], [
            Product::first(),
        ]);

        $response->assertRedirect('/products');

    }

Route:

Route::middleware([auth::class])->group(function () {
    Route::post('/cart/add/{product}', [CartController::class, 'addProductToCart'])->name('addProductToCart');
}

Controller:

 public function addProductToCart(Request $request, Product $product)
{
    return redirect()->route('products.index')->with('alert', 'Added product to cart');   
}

CodePudding user response:

addProductToCart is the name of the Method in the Controller, and the name of the Route, but the URL that actually calls that method is /cart/add/{product}. So, for this to work, you need to POST to that URL.

You can do that in a number of different ways:

$this->post("/cart/add/{$product->id}", ['quantity' => 4]);

// OR

$this->post(url("/cart/add/{$product->id}"), ['quantity' => 4]);

// OR

$this->post(route('addProductToCart', $product), ['quantity' => 4]);

You also need to define $product in your Test for this to work, something like:

$product = Product::factory()->create();

// OR

$product = Product::first();

So altogether, your Test would look like this:

public function test_user_can_add_product_to_cart() {
  $user = User::factory()->create();
  $product = Product::factory()->create();

  $this->actingAs($user);
  $response = $this->post(route('addProductToCart', $product), ['quantity' => 4]);

  $response->assertRedirect('/products');
}

CodePudding user response:

You need to use the route() helper in your test:

    public function test_user_can_add_product_to_cart()
    {
        $response = $this->post(route('addProductToCart'), ['quantity' => 4], [
            Product::first(),
        ]);

        ...
    }
  • Related