3

I'm trying to test a really simple increment function in vanilla javascript.

This function have a button with a click event, which triggers the input to sum one to its value.

I've tried to search for help to think how to resolve this problem. I think maybe I should create a mock for the button (instead of access the DOM element), and simulates the click event with Enzyme (but I don't know if it is really necessary).

All I could get in my searches was Jest testing using components from React or Angular, which complicated much more my question and therefore I get no answer for simple JS. The Jest documentation didn't help either.

The code of my function is:

const increment = () => {
  $increment.addEventListener("click", function() {
    if (+$quantity.value < 100) {
      $quantity.value = +$quantity.value + 1;
    }
  });
};

The full code is on this codesandbox.

1 Answer 1

2

Hokay so, my JavaScript is a little rusty but I think I know the problem looking at the code (thank you by the way, it made this way easier to figure out)...

Your instinct that you need a mock is correct, but right now the way your increment function works it's coupled to $increment which is in the local scope (making it really unfun to mock). Instead of using a private variable in the local scope to bind the event listener to, you want to pass the $element into the increment function, and then to add the event listener to it.

const increment = ($element) => {
  $element.addEventListener("click", function() {
    if (+$quantity.value < 100) {
      $quantity.value = +$quantity.value + 1;
    }
  });
};

In your test now you can create a mock with a function on it called addEventListener... the below is probably not quite right, but I think should get you most of the way there:

// In your test setup, or in the test itself

const myMockElement = {
  addEventListener: jest.fn(),
};

// Later in your test

increment(myMockElement);

expect(myMockElement.addEventListener.mock.calls.length).toBe(1);

Just as a note from the code in the event listener, I'd recommend passing it $quantity into the function as well instead of capturing it from the local context/scope/whatever-the-hell-its-exactly-called-in-javascript (i.e. what we did with $element)... it'll make testing things MUCH, MUCH easier to test and make your functions more robust.

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.