Assert.throws fails to identify error threw from controller

Hi guys! I’m failing to fulfill the following user story

  • convertHandler should correctly return an error on a double-fraction (i.e. 3/2/3 ).

It’s the first challenge of Quality Assurance Projects called Metric-Imperial-Converter

My rationale was: in the controller, I throw an error when provided a double fraction and in the unit test I verify if the error was successfully thrown. But I’m failing to achieve it :confused:

Here’s my code so far

The Controller

function ConvertHandler() {

  this.getNum = function(input) {
    let result = input.replace(/[a-zA-Z]/g, "");

    // Complies to Freecodecamp story: "should correctly default to a numerical input of 1 when no numerical input is provided."
    if(result === '') {
      return 1;
    }

    if(result.toString().includes("/")) {
      let fraction = result.split("/");
      if(fraction.length != 2) {
        throw new Error('invalid number'); // This part should throws the error that I'm trying to validate on my unit test
      } else {
        let firstNumber = Number.parseFloat(fraction[0]);
        let secondNumber = Number.parseFloat(fraction[1]);

        if(Number.isNaN(firstNumber) === false && Number.isNaN(secondNumber) === false) {
          result = eval(result);
        } else {
          throw new Error('invalid number');
        }
      }
    }

    if (result === null || result === undefined) {
      throw new Error('invalid number');
    }

    return result;
  };

The unit-tests.js

test('Testing if getNum throws an error if provided an invalid number', function() {
    assert.throws(convertHandler.getNum('3/5/7km'));
  });

This test is returning the following message:

1) Unit Tests
       Testing if getNum throws an error if provided an invalid number:
     Error: invalid number
      at ConvertHandler.getNum (controllers/convertHandler.js:14:15)
      at Context.<anonymous> (tests/1_unit-tests.js:16:32)

What am I doing wrong here?

My browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36

Challenge: Metric-Imperial Converter

Link to the challenge:

When you check something has thrown then you need to wrap the executed function in a callback. The callback will catch any thrown error. If it isn’t in a callback then there’s no way for the test to catch an error that comes specifically from the function you’re testing.

assert.throws(() => functionIExpectToThrow())

Can’t check the rest of the code to see if there’s any other issues atm, but you can’t do what you’re currently doing with the assertion

1 Like

Hey, DanCouper!

Thank you very much!! It totally worked :smile:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.