Kenneth_H's avatar

UnitTest/FeatureTest result differs from actual result from the browser

Hi I am currently coding an ecommerce project using TDD and have come to the point where I want to make sure that if a user for some reason bypasses the builtin browser validation to not add a negative quantity to the shopping cart. The way this is done is by having the Cartitem model implement a check in the save method. This checks if the quantity field is less than zero and if so, it throws an Exception. I could not find out why the total of the shopping cart was calculated, when there in fact should not be any items in the cart. My feature test looks like this:

    /** @test */
    public function a_user_cannot_add_a_negative_qty_to_the_cart()
    {
        $product = create(Product::class, ['id' => 123, 'price' => 500]);
        $this->json('POST', route('cart.store'), ['product_id' => $product->id, 'qty' => 1]);
        $response = $this->getjson(route('cart.show'));
        dd($response->json());
        $this->assertEquals(0, $response->json()['total']);
    }

When I run the test using phpunit, it fails as the assertion about the total value of the cart is 500 and not the expected 0. As I then thought that something must be wrong with my test, I decided to test this manually in the browser. So I opened the site and went to a product in order to add it to the cart. For this to work, I had to remove the browser validation attributes requiredand min=1, so that I could enter a negative value and then submit the form using axios. When I submit the form, I get a 500 error back, with the actual exception and the custom message that I have entered for it. If I then make a new axios.get to the route of the shopping cart, I then get a shopping cart with no items, as I would have expected.

I have the following set in the phpunit.xml:

    <php>
        <env name="APP_ENV" value="testing"/>
        <env name="DB_CONNECTION" value="sqlite"/>
        <env name="DB_DATABASE" value=":memory:"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="QUEUE_DRIVER" value="sync"/>
    </php>

In my normal .env, I also use sqlite for the database.

My unit test that tests if the exception is actually thrown looks like this:

    /** @test */
    public function a_negative_quantity_cannot_be_added_to_the_cart()
    {
        $this->expectException(\Exception::class);
        $cart = Cart::create();
        $product = create(Product::class, ['price' => 100]);

        $cart->addItem($product->id, -1);
    }

Can someone explain to me what I am missing here. Obviously, I must either miss something or be misunderstanding how some of this works.

I am btw. using the pre-release of Laravel 5.5. Could this be a bug?

0 likes
0 replies

Please or to participate in this conversation.