Brandon Sturgeon Brandon Sturgeon - 1 month ago 5x
Javascript Question

New to testing, how would I test this method with Mocha, Chai, Enzyme, and Sinon?

Here's my method

handleKeyEvent(event) {
const code = event.keyCode;

if (UsedKeys.includes(code)) {

if (code === KeyCodes.DOWN) {
} else if (code === KeyCodes.UP) {

I'm still pretty new to testing, and I have no idea how I'd go about testing this piece.
The method takes an event, so do I have to synthesize an event object and pass it in?

After that, do I just somehow test that
gets called?

This method doesn't return anything. Do I modify my code to be more testable?


There are a few ways you can do this.

  • You could create the object, and then spy on modifyRowIndexBy to check that it is called when handleKeyDown is called with the given parameter.
  • You could separate your key handling from your "index modifying" so that they can be tested independently (it is bad practice to spy on the same object that you are testing)
  • What does modifyIndexBy actually do? You could test that the outcome is the same (so it doesn't actually test that modifyIndexBy is called, but that what modifyIndexBy should do is done). This is a more BDD approach.