Search code examples
javascriptecmascript-6javascript-objectstemplate-literals

Console logging object values


As part of a bootcamp I am taking, I have been asked to create an online shopping cart. I am having such a problem with the addToCart function in the sense that I keep managing to to console log [{itemName: item, itemPrice: 8}] rather than 'item has been added to cart.

I think my problem lies in my template literal.

The aim is for the function to take in an item, create an object around it, apply additional properties, add to the cart array, console log that the item has been added (this is where my problem lies) then return the cart.

I have tried a number of alternatives such as trying to access the values via dot notation and using the key of the object to access the value. still have had no joy.

Below is my code:

function addToCart(item) {
  // write your code here
  var price = Math.floor(Math.random() * 100) + 1;
  var obj = {itemName: item, itemPrice: price};
  cart.push(obj);
  console.log(`${item} has been added to your cart.`)
  return cart;
}

What I am expecting is for the item that is being parsed into the function to be log to the console stating that the item has been added. I believe the rest of the code is working fine as it is passing the local tests.

The error I get is this:

Error: Expected [{itemName:'ice cream', itemPrice: 26}] to equal 'ice cream has been added to your cart.'

Any tips would be very helpful.


Solution

  • I had a look at your tests,

    Try following

    your test is (I hope I picked the right one) :

    it("returns a message indicating that the item has been added", function() {
        expect(addToCart("ice cream")).toEqual("ice cream has been added to your cart.");
    
        expect(addToCart("juice")).toEqual("juice has been added to your cart.");
      });
    

    Change your code to :

    function addToCart(item) {
      // write your code here
      var price = Math.floor(Math.random() * 100) + 1;
      var obj = {itemName: item, itemPrice: price};
      cart.push(obj);
      console.log(`${item} has been added to your cart.`)
      return `${item} has been added to your cart.`;
      //OR
      //return `${obj.itemName} has been added to your cart.`;
    }
    

    As you are comparing the returned value from "addToCart" in your test with the string in .toEqual so, so you should return that particular formatted string from your function.

    So instead of returning cart, you should return that particular string that you want to check.