JavaScript JavaScript Unit Testing Improving Our Tests Catching an Error

Georg Ekeberg
Georg Ekeberg
5,702 Points

Unable to find the right solution by testing for an error thrown

Here is my code. It says that you tried with something that should pass, but it failed. I have tried a lot of different things.

I get this message: Bummer: We tried your spec with a version of subtraction.js that DOESN'T work correctly, expecting the test to fail. But it passed! Better try again!

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

describe('subtraction', function () {
  var subtraction = require('../WHEREVER')  
  it('only works with numbers', function () {
    const errorMsg = "subtraction only works with numbers!"

    const handler0 = () => subtraction("one",2);
    const handler1 = () => subtraction(1, "two");
    const handler2 = () => subtraction("one", "two");

    const handlerB0 = () => subtraction(true,2);
    const handlerB1 = () => subtraction(1, true);
    const handlerB2 = () => subtraction(true, true);

    const handlerA0 = () => subtraction([1],2);
    const handlerA1 = () => subtraction(1, [2]);
    const handlerA2 = () => subtraction([1], [2]);

    const handlerO0 = () => subtraction({b:1},2);
    const handlerO1 = () => subtraction(1, {b:2});
    const handlerO2 = () => subtraction({b:1}, {b:2});

    const handlerx = () => subtraction(1,2);

    expect(handler0).to.throw(errorMsg);
    expect(handler1).to.throw(errorMsg);
    expect(handler2).to.throw(errorMsg);

    expect(handlerB0).to.throw(errorMsg);
    expect(handlerB1).to.throw(errorMsg);
    expect(handlerB2).to.throw(errorMsg);

    expect(handlerA0).to.throw(errorMsg);
    expect(handlerA1).to.throw(errorMsg);
    expect(handlerA2).to.throw(errorMsg);

    expect(handlerO0).to.throw(errorMsg);
    expect(handlerO1).to.throw(errorMsg);
    expect(handlerO2).to.throw(errorMsg);

    expect(handlerx).to.not.throw(errorMsg);
  })
})
subtraction.js
function subtraction (number1, number2) {
  if (typeof number1 !== 'number' || typeof number2 !== 'number') {
    throw Error('subtraction only works with numbers!')
  }
  return number1 - number2
}

1 Answer

Mark Sebeck
MOD
Mark Sebeck
Treehouse Moderator 25,357 Points

I did get it to pass if I write the function like Guil did

const handler0 = function() { subtraction("number",2); };
Georg Ekeberg
Georg Ekeberg
5,702 Points

Thank you! I guess it could not handle arrow functions. Was no problem locally.

Mark Sebeck
Mark Sebeck
Treehouse Moderator 25,357 Points

You're welcome. Glad you did it locally with arrow functions. I admire you trying! Keep at it.