It is really not clear what you are going for with your Sohalo
function. I've had to rewrite it to get a function that makes sense. At any rate, what you need to use to check whether the checks are happening is expect(fn).to.throw(...)
. The documentation for it is here. Note that when you want to check that a call with specific arguments throws an exception, the convenient way to do it is using bind
. So something like:
expect(Sohalo.bind(undefined, 1)).to.not.throw(Error, "Not a number");
will test the call Sohalo(1)
. (The first argument to bind
sets the value of this
inside the function, and we don't need it here so I'm leaving it undefined
).
So a file that would contain your function and test it could look something like this:
function Sohalo(partnerUserId) {
if (typeof partnerUserId !== "number" || isNaN(partnerUserId))
throw new Error("Not a number");
}
var chai = require("chai");
var expect = chai.expect;
describe("Sohalo", function() {
it('should fail if partnerUserId is not given', function(){
// This tests calling Sohalo with no arguments whatsoever.
expect(Sohalo).to.throw(Error, "Not a number");
});
it('should fail if partnerUserId is not a number', function(){
expect(Sohalo.bind(undefined, {})).to.throw(Error, "Not a number");
});
it('should fail if partnerUserId is NaN', function(){
expect(Sohalo.bind(undefined, NaN)).to.throw(Error, "Not a number");
});
it('should not fail if the partnerUserId is a literal number', function(){
expect(Sohalo.bind(undefined, 1)).to.not.throw(Error, "Not a number");
});
it('should not fail if the partnerUserId is a Number object', function(){
expect(Sohalo.bind(undefined, Number(10))).to.not.throw(Error, "Not a number");
});
});
In my test suites, I would typically perform tests with expect().to.throw
but not with expect().to.not.throw
. Instead of explicitly checking that the function does not throw, I'd just call it with good arguments and check that the results are correct. I'm using expect().to.not.throw
here only for the sake of illustration.