Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeError: getItem is not a function when testing a component with node module hooks

I am learning React, and got stuck in testing one of my components.
I use react-use-cart to manage the cart, this is how code looks

import React from "react";
import { Link } from "react-router-dom";
import { useCart } from "react-use-cart";
import PropTypes from "prop-types";

import handleQuantityChange from "../../logic/product/handleQuantityChange";

function AddToCart(props) {
    const {product, styles, loading} = props;
    const { addItem, inCart, getItem, updateItemQuantity } = useCart();
    const productInCart = getItem(product.id);

The test breaks at "productInCart = getItem(product.id)" saying " TypeError: getItem is not a function".
I’ve been stuck at this for several days, and would really appreciate some help, it’s my first time asking a question, so if you need any more info let me know, thank you.

Also about the test, test breaks on the render stage

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import React from "react";
import { render, screen } from "@testing-library/react";
import AddToCart from "../AddToCart";
import { MemoryRouter as Router } from "react-router-dom";
describe("get item is not a function", () => { 
    const product = {
        name: "test name",
        imgUrl: "test image",
        price: 555,
        shipping: 1000,
        id: 55
    }; 
    const styles = []


    beforeEach(() => {
        render(
            <Router>
                <AddToCart product={product} styles={styles}/>
            </Router>
        );
    });

>Solution :

You are missing CartProvider:

{...}

    beforeEach(() => {
        render(
          <CartProvider>
            <Router>
                <AddToCart product={product} styles={styles}/>
            </Router>
          </CartProvider>
        );
    });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading