dimanche 1 mars 2020

Testing React Functional Component (simple cart)

I am new into testing and I am trying to test a simple shop cart component with Jest and Enzyme. Below you can see a simplified version of the code. Mainly, Cart is getting the cart items by using useContext. Cart will show a summary of the items cost and the component Table will show all the items and the functionality (add or decrease the amount of items or remove them). Table uses useContext as well.

export const Cart = () => {
const { cartItems, clearCart } = useContext(CollectionContext);

const subtotal = cartItems.length
  ? cartItems.reduce((accumulator, currentItem) => {
      return accumulator + currentItem.price * currentItem.amount;
    }, 0)
  : 0;
const total = parseFloat((subtotal * (tax / 100 + 1)).toFixed(2));

return (
  <div>
    <Table />
    <div>
      <button onClick={() => clearCart()}>Clear cart</button>
      <p>Subtotal: {cartItems.length && subtotal}€</p>
      <p>Tax: {tax}%</p>
      <p>Total: {total}€</p>
    </div>
  </div>
  );
};

So far, I could only write this:

it("should list bought items", () => {
  const wrapper = mount(
    <CollectionProvider>
      <Router>
        <Cart />
      </Router>
    </CollectionProvider>
  );
});

But I have only an empty cart. I need to mock const { cart, clearCart } = useContext(CollectionContext); Once I get that, I should be able to test all the details and functionality. Could you please shed a light and let me know how to mock it? If my approach is wrong, please let me know as well. Tell me if you need the complete code or other details.

Aucun commentaire:

Enregistrer un commentaire