lundi 16 novembre 2020

mocking jquery $ and its functions with jest (or any other technique)

I have some javascript that uses jquery:

  var $newItemButton = $('#newItemButton');
  var $newItemForm = $('#newItemForm');
  var $textInput = $('input:text');

  $newItemButton.show();
  $newItemForm.hide();

    $('#showForm').on('click', function(){
    console.log("SHOW FORM CLICKED");
    $newItemButton.hide();
    $newItemForm.show();
  });

  $newItemForm.on('submit', function(e){
    e.preventDefault();
    var newText = $textInput.val();
    $('li:last').after('<li>' + newText + '</li>');
    $newItemForm.hide();
    $newItemButton.show();
    $textInput.val('');
  });

I would like to verify that the hide() is called on $newItemButton using jest if possible (or any other technique).

Something like this

    var spy = jest.spyOn($.fn, 'hide').mockImplementation(() =>{});
    $('#showForm').click();
    expect(spy).toHaveBeenCalled();

but not hide() on all objects just on $newItemButton. So, in general, my question is how does one mock/spy on jquery $ and its various functions so as to control them in unit tests?

Aucun commentaire:

Enregistrer un commentaire