0
 const sum = (a) => {
    try{
      return a + a
    } catch(e){
     console.log('error: ', e )
    }
}
module.exports = sum

I have written the test for this function as shown below. How will can I test for catch in the above code?

const sum = require('./add')

describe('sum', () => {
  test('should add', () => {
      const summ = sum(4)
      console.log(summ)
      expect(summ).toBe(8)
  })
})
Stephen Gatana
  • 118
  • 1
  • 6

1 Answers1

0

Your function sum returns the sum a+a or undefined if the catch block is entered. You would like to know if the catch block is accessed: it will never be (or in some very special cases...)

It will never throw an error whatever input you may have on sum the try: the reason is that the value of a is coerced implicitly to make the concatenation operation possible:

const sum = (a) => {
  try {
    return a + a
  } catch (e) {
    console.log('error: ', e)
  }
}

console.log(sum())            // NaN
console.log(sum(() => {}))    // () => {}() => {}
console.log(sum(NaN))         // NaN
console.log(sum(undefined))   // NaN
console.log(sum(true))        // 2
console.log(sum({}))          // [object Object][object Object]
console.log(sum([]))          //
console.log(sum(1))           // 2
.as-console-wrapper { max-height: 100% !important; top: 0; }

So maybe you would like to test if the input is an integer:

const sum = (a) => {
  if(Number.isInteger(a)) {
    return a + a;  
  } else {
    throw 'Parameter is not an integer';
  }
}

Which will result in:

sum()            // "Uncaught Parameter is not an integer"
sum(() => {})    // "Uncaught Parameter is not an integer"
sum(NaN)         // "Uncaught Parameter is not an integer"
sum(undefined)   // "Uncaught Parameter is not an integer"
sum(true)        // "Uncaught Parameter is not an integer"
sum({})          // "Uncaught Parameter is not an integer"
sum([])          // "Uncaught Parameter is not an integer"
sum(1)           // 2

Here's an example using try...catch:

const sum = (a) => {
  if (Number.isInteger(a)) {
    return a + a;
  } else {
    throw 'Parameter is not an integer';
  }
}

try {
  sum('no good argument');
} catch (e) {
  console.log(e);
}
Ivan
  • 34,531
  • 8
  • 55
  • 100
  • 2
    It would be *really strange*, but it's *possible* for an error to be thrown when calling the original `sum`: pass it `const obj = { valueOf() { throw new Error('err!'); } };` – CertainPerformance Jun 30 '18 at 09:17
  • ah ah yes indeed, I didn't think of that *edge* case ;) – Ivan Jun 30 '18 at 09:20