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

Fábio Nascimento
Fábio Nascimento
10,418 Points

What is wrong with my code?

Why is this not passing?

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

describe('subtraction', function () {
  var subtraction = require('../WHEREVER')  
  it('only works with numbers', function () {
    // YOUR CODE HERE
    expect(subtraction('a', 'b').to.throw('subtraction only works with numbers!');
  })
})
subtraction.js
function subtraction (number1, number2) {
  if (typeof number1 !== 'number' || typeof number2 !== 'number') {
    throw Error('subtraction only works with numbers!')
  }
  return number1 - number2
}
Ante Adamović
seal-mask
.a{fill-rule:evenodd;}techdegree
Ante Adamović
Front End Web Development Techdegree Student 2,508 Points

I'm not an expert but if the code is correct it's not suppose to pass. If the output is 'subtraction only works with numbers!' then the code is doing what it's suppose to ^_^

1 Answer

Marco Amadio
Marco Amadio
4,882 Points

The problem may be that you're trying to call the "subtraction" function in your code indeed. What you need is to pass the "subtraction" function into an anonymous function, like this:

expect(function () { subtraction('a', 'b') }).to.throw('subtraction only works with numbers!');

Also, you can use function.bind:

expect(subtraction.bind(null, 'a', 'b')).to.throw('subtraction only works with numbers!');

Where the first argument is passed as "this" parameter and other arguments are the function's parameter.

Last but not least, if your function have no parameters, your code will be something like:

/* Your function */

var fn = function () {
  throw Error('subtraction only works with numbers!');
}

/* Then in your test code */

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

Hope it helps.

This worked! Thanks. I was having problems with Chai. I didn't realize I needed to wrap "subtraction('dog', 'cat')" in an anonymous function to get it to work due to it having parameters.