You are here

public function CartCheckoutTest::testCartApi in Ubercart 8.4

Tests cart API.

File

uc_cart/tests/src/Functional/CartCheckoutTest.php, line 69

Class

CartCheckoutTest
Tests the cart and checkout functionality.

Namespace

Drupal\Tests\uc_cart\Functional

Code

public function testCartApi() {

  // Test the empty cart.
  $items = $this->cart
    ->getContents();
  $this
    ->assertEquals([], $items, 'Cart is an empty array.');

  // Add an item to the cart.
  $this->cart
    ->addItem($this->product
    ->id());
  $items = $this->cart
    ->getContents();
  $this
    ->assertCount(1, $items, 'Cart contains one item.');
  $item = reset($items);
  $this
    ->assertEquals($this->product
    ->id(), $item->nid->target_id, 'Cart item nid is correct.');
  $this
    ->assertEquals(1, $item->qty->value, 'Cart item quantity is correct.');

  // Add more of the same item.
  $qty = mt_rand(1, 100);
  $this->cart
    ->addItem($this->product
    ->id(), $qty);
  $items = $this->cart
    ->getContents();
  $this
    ->assertCount(1, $items, 'Updated cart contains one item.');
  $item = reset($items);
  $this
    ->assertEquals($qty + 1, $item->qty->value, 'Updated cart item quantity is correct.');

  // Set the quantity and data.
  $qty = mt_rand(1, 100);
  $item->qty->value = $qty;
  $item->data->updated = TRUE;
  $item
    ->save();
  $items = $this->cart
    ->getContents();
  $item = reset($items);
  $this
    ->assertEquals($qty, $item->qty->value, 'Set cart item quantity is correct.');
  $this
    ->assertTrue($item->data->updated, 'Set cart item data is correct.');

  // Add an item with different data to the cart.
  $this->cart
    ->addItem($this->product
    ->id(), 1, [
    'test' => TRUE,
  ]);
  $items = $this->cart
    ->getContents();
  $this
    ->assertCount(2, $items, 'Updated cart contains two items.');

  // Remove the items.
  foreach ($items as $item) {
    $item
      ->delete();
  }
  $items = $this->cart
    ->getContents();
  $this
    ->assertCount(0, $items, 'Cart is empty after removal.');

  // Empty the cart.
  $this->cart
    ->addItem($this->product
    ->id());
  $this->cart
    ->emptyCart();
  $items = $this->cart
    ->getContents();
  $this
    ->assertEquals([], $items, 'Cart is emptied correctly.');
}