Need help for unit test cases for below code

/**

 * Function to toggle the checkbox when user Hits Enter key from keyboard

 */

 const methodName = () => {

  const conditionCheck = document.getElementById('ID');

  if(conditionCheck) {

    conditionCheck.addEventListener('keypress', function (event) {

      if (event.type === 'keypress' && event.code === 'Enter') {

        conditionCheck.checked = !conditionCheck.checked;

      }

    });

  }

};

if (document.readyState !== "loading") {

  methodName();

}

else {

  document.addEventListener('DOMContentLoaded', methodName);

}

export { methodName };

Hello and welcome to the freeCodeCamp forums. I’ve reposted your code below, since something seems to have gone wrong with your formatting in your first post.

/**

    Function to toggle the checkbox when user Hits Enter key from keyboard

*/

const methodName = () => {

const conditionCheck = document.getElementById(‘ID’);

if(conditionCheck) {

conditionCheck.addEventListener('keypress', function (event) {

  if (event.type === 'keypress' && event.code === 'Enter') {

    conditionCheck.checked = !conditionCheck.checked;

  }

});

}

};

if (document.readyState !== “loading”) {

methodName();

}

else {

document.addEventListener(‘DOMContentLoaded’, methodName);

}

export { methodName };

Also, could you go a bit more in depth about your problem? What test cases are you trying to solve?

For unit test cases to mock function and if condition to get 100% coverage using JEST.

test(`Method `, () => {

    const spy = jest.spyOn(method, 'methodName');

    method.methodName();

    expect(spy).toHaveBeenCalled();

})

Reaching 50% coverage

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Any one have solution for this to get 100% coverage ???

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.