How to Test a Cart Item Component With a Remove Button
Get the project source code below, and follow along with the lesson material.
Download Project Source CodeTo set up the project on your local machine, please follow the directions provided in the README.md
file. If you run into any issues with running the project source code, then feel free to reach out to the author in the course's Discord channel.
This lesson preview is part of the Fullstack React with TypeScript Masterclass course and can be unlocked immediately with a single-time purchase. Already have access to this course? Log in here.
Get unlimited access to Fullstack React with TypeScript Masterclass with a single-time purchase.

[00:00 - 00:11] Cart item component. This component renders the product information for the products added to the cart. It has the product image, product name, the price, and a button to remove the product from the cart.
[00:12 - 00:27] Let's write tests for it. Open SRC Cart, create a new file, Cart Item. spec.tsx. We'll want to test that it renders correctly and when you click the Remove button, it removes the item from the cart.
[00:28 - 00:45] Write the top level describe block inside with we plan to test it to do to test that it renders correctly. And then describe on remove click. Here we'll test that it calls the past in function.
[00:46 - 01:03] We'll need the product data. Let's hard code it in the top level describe block , const product. Of type product is an object containing name, product, full price, 100, and image, image, source, PNG.
[01:04 - 01:28] Now let's test that it renders correctly. Add a callback. Here we want to get the container and get by alt text to find our image. We call render with router passing the rendering function that will render cart item passing the mocked product, product equals product, and remove from cart should be a void function.
[01:29 - 01:43] Now we expect that container inner HTML will contain product full. We also expect that inner HTML will have text 100 zorkmits.
[01:44 - 02:01] And we also expect that get by alt text product full will have attribute as our C that equals image source PNG. The test is passing so we can continue with the on remove click at the callback .
[02:02 - 02:27] In this test, we'll want to mock the remove from cart function. Mock it using the just the fan render our component will want the get by text function equals render with router passing the function that will render cart item with product and the remove from cart function where we pass remove from cart mock.
[02:28 - 02:45] Then we click the remove button, click get by text remove. And then we expect that remove from cart mock was called with the product that was passed there as an argument. Wait for the test to execute and it's passing.