jeudi 31 mai 2018

Constructor functionality fails to path jest test

I have the following constructor that should be modified in order to pass JEST testings.

(function() {
  var MODULE_NAME = 'shoppingcartModel',
      _VATRate =  20,
      _getCart;

  window[MODULE_NAME] = function() {
    _getCart = function() {
      return {
        products: [],
        total: {
          beforeVAT: 0,
          afterVAT: 0,
          VAT: 0
        }
    };

    return {
      init: function(VATRate) {
        return _Cart.total.VAT = VATRate || 0;
      },

      getCart: _getCart,

      addProducts: function(newOrExistingProducts) {
        return _Cart.products.push(newOrExistingProducts);
      },

      ... other stuff
    };
  };
})()

And the test describes the following way

describe(`NO product added`, () => {
  test(`cart`, () => {
    const instance = window[MODULE_NAME]();
    const emptyCart = {
      products: [],
      total: {
        beforeVAT: 0,
        afterVAT: 0,
        VAT: 0
      }
    }

    instance.init();
    expect(instance.getCart()).toEqual(emptyCart);
  });
});

describe(`ONE product added`, () => {
  const _VATRate = 20
  const _product = {
    name: 'product1',
    price: 1.50,
    quantity: 1
  };
  let _instance
  let _cart

  beforeEach(() => {
    _instance = window[NETCENTRIC_NAMESPACE][MODULE_NAME]();
    _instance.init(_VATRate);
    _cart = _instance.addProducts(_product);
  });

  test(`cart's products`, () => {
    expect(_cart.products).toEqual([_product]);
  });
});

I've modified the constructor the following way so it passes the 1st part and successfully adds an item.

(function() {
  var MODULE_NAME = 'shoppingcartModel',
      _VATRate =  20,
      _Cart = {
        products: [],
        total: {
          beforeVAT: 0,
          afterVAT: 0,
          VAT: 0
        }
      },
      _getCart;

  window[MODULE_NAME] = function() {
    _getCart = function() {
      return {
        total: _Cart.total,
        products: _Cart.products
      };
    };

    return {
      init: function(VATRate) {
        return _Cart.total.VAT = VATRate || 0;
      },

      getCart: _getCart,

      addProducts: function(newOrExistingProducts) {
        return _Cart.products.push(newOrExistingProducts);
      }
    };
  };
})()

var shoppingCart = new window.shoppingcartModel()


shoppingCart.init(20);
shoppingCart.addProducts('Coffee, 2$');
console.log(shoppingCart.getCart())

But unfortunately, my implementation doesn't satisfy the 2nd part of test needs. And it's terminal window it communicates with:

Expected value to equal:
      [{"name": "product1", "price": 1.5, "quantity": 1}]
    Received:
      undefined

Can you please suggest what can be done? :)

Aucun commentaire:

Enregistrer un commentaire