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?

var expect = require('chai').expect

describe('subtraction', function () {
  var subtraction = require('../WHEREVER')  
  it('only works with numbers', function () {
    expect(subtraction('a', 'b').to.throw('subtraction only works with numbers!');
function subtraction (number1, number2) {
  if (typeof number1 !== 'number' || typeof number2 !== 'number') {
    throw Error('subtraction only works with numbers!')
  return number1 - number2
Ante Adamović
Ante Adamović
Front End Web Development Techdegree Student 2,507 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.

Joshua Kelly
Joshua Kelly
18,202 Points

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.