Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Unit Testing Improving Our Tests Catching an Error

"Bummer: We tried your spec with a version of subtraction.js that DOESN'T work correctly, expecting the test to fail..."

Not sure why my test would pass when it shouldn't. My code here looks almost exactly like the code I wrote for the project...

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

describe('subtraction', function() {
  const subtraction = require('../WHEREVER')  
  it('only works with numbers', function() {
    const handler = () => subtraction(null, {});

    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
}

UPDATE:

So apparently I did two things wrong:

1.) I didn't export the subtraction function. It never occured to me to do so because I wasn't being tested on exporting functions. Seems pretty stupid but okay.

2.) I used an arrow function. I don't see what the problem is with writing my handler as an arrow function. Does anyone have any idea why treehouse would want the handler function to be written in the regular syntax?

2 Answers

var expect = require('chai').expect

describe('subtraction', function () {
  var subtraction = require('../WHEREVER') 

  it('only works with numbers', function () {
  var handler = function (){subtraction('string1', 'string2');};
    expect(handler).to.throw(Error);

  })
})

This worked for me, hope it helps.

I think the arrow function should be written as:

const handler = () => { subtraction(null, {}); };

I tried writing my arrow function like that before and it didn't work.

Thanks for the reply though.

Dario Bahena
Dario Bahena
10,697 Points

If you read the documentation, mocha does not like arrow functions. Although I am not quite sure why it would not work within its own context... It might be due to how 'this' is treated in arrow function expressions and regular function expressions. Regardless, I don't see a reason why this shouldn't work.

const handler = () => subtraction('s','a');