Jest Testing CartProvider Example
nursahketene opened this issue · comments
I want to write a test which basically checks the total cart item number is currently visible.
So in my _app.js I have something like this
// _app.js
return (
<CartProvider>
<Component />
</CartProvider>
);
On my product page I have function to update the cart
// product.js
const addItem = () => {
addItem(product);
}
return (
<>
<span>{totalItems}</span>
<button onClick={addItem}>Add</button>
</>
);
And in my test I would like to test the total items
describe("Add Item", () => {
beforeEach(() => {
render(
<CartProvider>
<Product product={product} />
</CartProvider>
);
});
it("Count should increase by one!", () => {
const count = screen.getByTestId("cart-count");
expect(count.textContent).toBe("0");
const button = screen.getByTestId("add-button");
userEvent.click(button);
expect(count.textContent).toBe("1");
});
it("Count should increase by one for a different user flow!", () => {
const count = screen.getByTestId("cart-count");
expect(count.textContent).toBe("0");
const button = screen.getByTestId("add-button");
userEvent.click(button);
expect(count.textContent).toBe("1");
});
});
However in this case I will get an error as the second test condition for checking 0 count is not correct. It will receive 1 as a total number of items.
Is there a way that I can clean the cart before each test in afterEach()
Hey @nursahketene
You could do something similar like I did here: https://github.com/notrab/react-use-cart/blob/main/test/index.test.tsx#L15
You could also pass a unique ID to the CartProvider which will make sure it's set empty, as it won't attach to an existing one if is a unique value is given.
Perfect. thank you I was looking for this :D cleaning the window locale is a good solution for me :D