• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

magento / pwa-studio / #25627

08 Sep 2025 11:02AM UTC coverage: 85.621%. First build
#25627

Pull #4545

codebuild

del15881
Fixing Failing Test Cases for ADD TO CART Dialog box
Pull Request #4545: Enhancement/pwa 3550

5262 of 6570 branches covered (80.09%)

Branch coverage included in aggregate %.

50 of 80 new or added lines in 5 files covered. (62.5%)

13280 of 15086 relevant lines covered (88.03%)

29.49 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

79.1
/packages/peregrine/lib/talons/Gallery/useAddToCartButton.js
1
import { useCallback, useState } from 'react';
2
import { useMutation, gql } from '@apollo/client';
3
import { useHistory } from 'react-router-dom';
4

5
import { useCartContext } from '../../context/cart';
6
import { useEventingContext } from '../../context/eventing';
7
import resourceUrl from '../../util/makeUrl';
8
import operations from './addToCart.gql';
9
import { useAwaitQuery } from '@magento/peregrine/lib/hooks/useAwaitQuery';
10
import BrowserPersistence from '../../util/simplePersistence';
11

12
/**
13
 * @param {String} props.item.uid - uid of item
14
 * @param {String} props.item.name - name of item
15
 * @param {String} props.item.stock_status - stock status of item
16
 * @param {String} props.item.__typename - product type
17
 * @param {String} props.item.url_key - item url key
18
 * @param {String} props.item.sku - item sku
19
 *
20
 * @returns {
21
 *      handleAddToCart: Function,
22
 *      isDisabled: Boolean,
23
 *      isInStock: Boolean
24
 * }
25
 *
26
 */
27
const UNSUPPORTED_PRODUCT_TYPES = [
2✔
28
    'VirtualProduct',
29
    'BundleProduct',
30
    'GroupedProduct',
31
    'DownloadableProduct'
32
];
33

34
const CREATE_CART_MUTATION = gql`
2✔
35
    mutation createCart {
36
        cartId: createEmptyCart
37
    }
38
`;
39

40
const CART_DETAILS_QUERY = gql`
2✔
41
    query checkUserIsAuthed($cartId: String!) {
42
        cart(cart_id: $cartId) {
43
            id
44
        }
45
    }
46
`;
47

48
export const useAddToCartButton = props => {
2✔
49
    const { item, urlSuffix } = props;
21✔
50

51
    const [, { dispatch }] = useEventingContext();
21✔
52

53
    const [isLoading, setIsLoading] = useState(false);
21✔
54

55
    const [cartState, cartApi] = useCartContext();
21✔
56
    const { cartId } = cartState;
21✔
57

58
    const [fetchCartId] = useMutation(CREATE_CART_MUTATION);
21✔
59
    const fetchCartDetails = useAwaitQuery(CART_DETAILS_QUERY);
21✔
60

61
    const isInStock = item.stock_status === 'IN_STOCK';
21✔
62

63
    const productType = item
21!
64
        ? item.__typename !== undefined
21!
65
            ? item.__typename
66
            : item.type
67
        : null;
68

69
    const isUnsupportedProductType = UNSUPPORTED_PRODUCT_TYPES.includes(
21✔
70
        productType
71
    );
72

73
    const isDisabled = isLoading || !isInStock || isUnsupportedProductType;
21✔
74

75
    const history = useHistory();
21✔
76

77
    const [addToCart] = useMutation(operations.ADD_ITEM);
21✔
78

79
    // helper: ensure we have a valid cartId before adding
80
    const ensureCartId = useCallback(async () => {
21✔
81
        let newCartId = cartId;
3✔
82
        if (!newCartId) {
3!
NEW
83
            console.log('No cart ID found, creating a new cart...');
×
NEW
84
            await cartApi.getCartDetails({
×
85
                fetchCartId,
86
                fetchCartDetails
87
            });
88

NEW
89
            newCartId = new BrowserPersistence().getItem('cartId');
×
90

NEW
91
            if (!newCartId) {
×
NEW
92
                throw new Error('Failed to create a new cart');
×
93
            }
94
        }
95
        return newCartId;
3✔
96
    }, [cartId, cartApi, fetchCartId, fetchCartDetails]);
97

98
    const handleAddToCart = useCallback(async () => {
21✔
99
        try {
8✔
100
            if (productType === 'SimpleProduct' || productType === 'simple') {
8✔
101
                setIsLoading(true);
3✔
102

103
                const quantity = 1;
3✔
104
                let newCartId;
105

106
                if (item.uid) {
3!
107
                    // ensure cart right before addToCart
108
                    newCartId = await ensureCartId();
3✔
109

110
                    await addToCart({
3✔
111
                        variables: {
112
                            cartId: newCartId,
113
                            cartItem: {
114
                                quantity,
115
                                entered_options: [
116
                                    {
117
                                        uid: item.uid,
118
                                        value: item.name
119
                                    }
120
                                ],
121
                                sku: item.sku
122
                            }
123
                        }
124
                    });
125
                } else {
126
                    // ensure cart right before addToCart
NEW
127
                    newCartId = await ensureCartId();
×
128

129
                    await addToCart({
×
130
                        variables: {
131
                            cartId: newCartId,
132
                            cartItem: {
133
                                quantity,
134
                                sku: item.sku
135
                            }
136
                        }
137
                    });
138
                }
139

140
                dispatch({
2✔
141
                    type: 'CART_ADD_ITEM',
142
                    payload: {
143
                        cartId: newCartId,
144
                        sku: item.sku,
145
                        name: item.name,
146
                        pricing: {
147
                            regularPrice: {
148
                                amount:
149
                                    item.price_range.maximum_price.regular_price
150
                            }
151
                        },
152
                        priceTotal:
153
                            item.price_range.maximum_price.final_price.value,
154
                        currencyCode:
155
                            item.price_range.maximum_price.final_price.currency,
156
                        discountAmount:
157
                            item.price_range.maximum_price.discount.amount_off,
158
                        selectedOptions: null,
159
                        quantity
160
                    }
161
                });
162

163
                setIsLoading(false);
2✔
164
            } else if (
5✔
165
                productType === 'ConfigurableProduct' ||
9✔
166
                productType === 'configurable'
167
            ) {
168
                const productLink = resourceUrl(
1✔
169
                    `/${item.url_key}${urlSuffix || ''}`
1!
170
                );
171

172
                history.push(productLink);
1✔
173
            } else {
174
                console.warn('Unsupported product type unable to handle.');
4✔
175
            }
176
        } catch (error) {
177
            console.error(error);
1✔
178
        }
179
    }, [
180
        productType,
181
        addToCart,
182
        item,
183
        dispatch,
184
        history,
185
        urlSuffix,
186
        ensureCartId
187
    ]);
188

189
    return {
21✔
190
        handleAddToCart,
191
        isDisabled,
192
        isInStock
193
    };
194
};
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc