简体   繁体   中英

How do I write a test for a function that should do nothing?

Sometimes, I write functions that, under certain circumstances, should do nothing. Not only is it acceptable that they don't do anything, but it is actually the required behavior. Is there a pattern to test a function to make sure it has no side effects?


As an example, I'm currently testing a function that looks like this:

function onRowOfIconsClicked(iconName) {
  if (iconName === 'new') {
    doSomeAwesomeStuffImAlreadyTesting();
  }
  // We haven't implemented the other icons yet, so for now,
  // do nothing and don't throw an error if a different icon
  // is clicked
}

How would I write a test case to assert the current requirement that when onRowOfIconsClicked is called with an iconName other than "new" , the function does nothing?

All JavaScript functions have a return value, even if that return value is undefined because of no explicit return statement used to specify a return value.

What you can do then, is test that if the function is called with an iconName parameter other than 'new' , then test that the function returns undefined . Because undefined === undefined and so will pass the test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM