Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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.