JavaScript JavaScript Unit Testing Improving Our Tests Catching an Error

Nikola Brežnjak
Nikola Brežnjak
10,897 Points

The subtraction function in subtraction.js throws an error if it's called with anything other than numbers.

This is the challenge task 1 of 1 and it goes like this:

The subtraction function in subtraction.js throws an error if it's called with anything other than numbers. Write a spec that will test for this behavior. Make sure to check for subtraction's specific error message! Check the Chai docs if you need help.

I tried various things in subtraction_spec.js like expect(subtraction('a', 'b').to.throw(Error);

but these don't seem to pass.

Any help is appreciated!

subtraction_spec.js
var expect = require('chai').expect

describe('subtraction', function () {
  var subtraction = require('../subtraction')  
  it('only works with numbers', function () {

    expect(subtraction()).to.throw('subtraction only works with numbers!');

  })
})
subtraction.js
function subtraction (number1, number2) {
  throw Error('subtraction only works with numbers!')
  if (typeof number1 !== 'number' || typeof number2 !== 'number') {
    throw Error('subtraction only works with numbers!')
  }
  return number1 - number2
}

3 Answers

Mikis Woodwinter
Mikis Woodwinter
44,939 Points

Hey Nikola,

You almost got it; you just missed a detail vis-à-vis the ChaiJS Expect API. The correct implementation looks like this:

var expect = require('chai').expect

describe('subtraction', function () {
  var subtraction = require('../WHEREVER')  
  it('only works with numbers', function () {
    // YOUR CODE HERE
    expect(function () {
      subtraction()
    }).to.throw('subtraction only works with numbers!');
  })
})
Nikola Brežnjak
Nikola Brežnjak
10,897 Points

Thank you. Yes, I have totally missed that. Thanks for pointing it out and helping so quickly.

makes no sense.. why doesn't expect(subtract('A','B')).to.be.Error; not work?

Ben Newton
Ben Newton
14,726 Points

I also don't understand why "var subtraction = require('../WHEREVER')" is valid. I corrected it to what I thought it should be and that was the bottleneck causing my test not to pass