I am making an Amazon project and I encountered a problem when i try to test addToCart function with Jasmine. The only issue that prevents it from working is that it can't acces the "value" in addToCart function.
const quantity = Number(selectQuantityElement.value);
Jasmine gives this error message: TypeError: Cannot read properties of null (reading 'value')
Is there a way maybe to simulate that i selected some value in selector so it knows it's a number? Or to acces "value" from the test case?
When I change a value of quantity to some number it works:
const quantity = 2;
Here is the test case:
import {addToCart, cart, loadFromStorage} from '../../data/cart.js';
describe('test suite: addToCart', () => {
const productId = 'e43638ce-6aa0-4b85-b27f-e1d07eb678c6';
it('adds an existing product to the cart', () => {
document.querySelector('.js-test-container').innerHTML = `
<div class="js-added-to-cart-text-${productId}"></div>
<div class="js-quantity-selector"></div>
`
spyOn(localStorage, 'setItem');
spyOn(localStorage, 'getItem').and.callFake(() => {
return JSON.stringify([{
productId: 'e43638ce-6aa0-4b85-b27f-e1d07eb678c6',
quantity: 1,
deliveryOptionId: '1'
}]);
});
loadFromStorage();
addToCart('e43638ce-6aa0-4b85-b27f-e1d07eb678c6');
expect(cart.length).toEqual(1);
expect(localStorage.setItem).toHaveBeenCalledTimes(1);
expect(cart[0].productId).toEqual('e43638ce-6aa0-4b85-b27f-e1d07eb678c6');
expect(cart[0].quantity).toEqual(2);
});
And here is the addToCart function:
export function addToCart(productId) {
displayAddedMessage(productId);
const selectQuantityElement = document.querySelector(`.js-quantity-selector-${productId}`)
const quantity = Number(selectQuantityElement.value); <-- This value
let matchingItem;
cart.forEach((cartItem) => {
if (productId === cartItem.productId) {
matchingItem = cartItem;
}
});
if (matchingItem) {
matchingItem.quantity += quantity;
} else {
cart.push({
productId: productId,
quantity: quantity,
deliveryOptionId: '1'
})
}
saveToStorage();
}
And here is the HTML for the selector:
<div class="product-quantity-container js-product-quantity-container">
<select class="js-quantity-selector-${product.id} js-quantity-selector">
<option selected value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
</div>