Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Unit Testing Improving Our Tests Catching an Error

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

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!');
  })
})

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