Skip to content

Commit f24ee60

Browse files
authored
feat: Allow adding free items to the cart (#48)
* Check for absence of price key instead of a non-truthy value Changes the addItem method so that when you add a new item, when we check the price key, instead of checking when the price is non-truthy, we check if the key exists in the object. This allows the addition of 0 value prices. * Added test
1 parent fba660e commit f24ee60

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ export function CartProvider({
131131

132132
const currentItem = state.items.find((i) => i.id === item.id);
133133

134-
if (!currentItem && !item.price)
134+
if (!currentItem && !item.hasOwnProperty("price"))
135135
throw new Error("You must pass a `price` for new items");
136136

137137
if (!currentItem) {

index.test.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,29 @@ describe("addItem", () => {
8787
expect(result.current.items).toHaveLength(1);
8888
expect(result.current.totalItems).toBe(1);
8989
expect(result.current.totalUniqueItems).toBe(1);
90+
expect(result.current.cartTotal).toBe(1000);
91+
expect(result.current.isEmpty).toBe(false);
92+
});
93+
94+
test("allows free item", () => {
95+
const wrapper = ({ children }) => (
96+
<CartProvider id="test">{children}</CartProvider>
97+
);
98+
99+
const { result } = renderHook(() => useCart(), {
100+
wrapper,
101+
});
102+
103+
const item = { id: "test", price: 0 };
104+
105+
act(() => {
106+
result.current.addItem(item);
107+
});
108+
109+
expect(result.current.items).toHaveLength(1);
110+
expect(result.current.totalItems).toBe(1);
111+
expect(result.current.totalUniqueItems).toBe(1);
112+
expect(result.current.cartTotal).toBe(0);
90113
expect(result.current.isEmpty).toBe(false);
91114
});
92115

0 commit comments

Comments
 (0)