JavaScript JavaScript Unit Testing Improving Our Tests Catching an Error

Ivan Sardelić
Ivan Sardelić
Full Stack JavaScript Techdegree Graduate 18,248 Points

I don't see what I'm missing here :/

I've exported the subtraction function in the module, required it with the correct path, called the function with inadequate parameters in the handler, I can't see why this wouldn't work

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

describe('subtraction', function () {
  var subtraction = require('../subtraction.js').subtraction  
  it('only works with numbers', function () {

    let handler = function() {subtraction(undefined,undefined)}

    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
}

module.exports = {
    subtraction: subtraction
}

1 Answer

This one was tricky. I've never tried to work in a test suite outside of an actual development environment. It's really frustrating that treehouse doesn't show your testing results or even what they are testing that made you fail. It also doesn't help that the error messages are not very descriptive.

I highly recommend setting up your own test environment so you can see a detailed test log of the results you're receiving or do your testing in a workspace on treehouse.

The test was much more simple than it seemed.

var expect = require('chai').expect

describe('subtraction', function () {
// this is the first thing that threw me. We have no idea where the 'subtraction.js' file lives.
// in relation to subtraction_spec.js
  var subtraction = require('../WHEREVER')  //leave this line alone
  it('only works with numbers', function () {
        // this was the only mistake you made. You can either use var or const
       // let won't work for the handler.
        const handler = function() {subtraction(undefined,undefined)}

        expect(handler).to.throw(Error);
        expect(handler).to.throw('subtraction only works with numbers!');
  })
})
Ivan Sardelić
Ivan Sardelić
Full Stack JavaScript Techdegree Graduate 18,248 Points

Thanks a lot my friend! I spent so much time on this, I will definitely be doing my testing in a dev environment from now on. Thanks once again! Cheers