JavaScript JavaScript Unit Testing Improving Our Tests Catching an Error

Kaitlyn Dodds
Kaitlyn Dodds
32,543 Points

Can't figure out why my solution doesn't pass.

It would seem like my solution would work. I have tested it on my own computer and it catches the error nicely.

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

describe('subtraction', function () {
  var subtraction = require('../WHEREVER')  
  it('only works with numbers', function () {
    let handler = function () { subtraction('some', 'num'); };
    expect(handler).to.throw(Error);
    expect(handler).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
}

3 Answers

Jesus Mendoza
Jesus Mendoza
23,273 Points

Hi Kaitlyn,

If you rewatch the previous video you can see that Guil wraps the function that throws an error inside a function called handler and then executes the test again that function handler:

var expect = require('chai').expect

describe('subtraction', function () {
  var subtraction = require('../WHEREVER')  
  it('only works with numbers', function () {
    // YOUR CODE HERE
    var handler = function() { subtraction('1', '2'); };

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

That should work

Kaitlyn Dodds
Kaitlyn Dodds
32,543 Points

I do have a handler function. The only difference being I used let rather than var...

Kaitlyn Dodds
Kaitlyn Dodds
32,543 Points

I also copied and pasted your answer, and it still doesn't work.

Is this challenge broken?

Jesus Mendoza
Jesus Mendoza
23,273 Points

That's weird. I just tried it and it works perfectly

Jesus Mendoza
Jesus Mendoza
23,273 Points

I changed the let with var in your code and it works fine