Chai, testing that function throws correct error

1.3k Views Asked by At

Basically, I am practicing testing with Mocha and I wrote a schema where a serial number is supposed to be unique. I want a test that shows that when I try to use that serial number again, it throws the Mongo Error E11000 for duplicate keys.

phaseSchema.statics.createPhase = function(name,sernum,desc){
  var phase = mongoose.model('phases', phaseSchema)
  var newphase = new phase({NAME: name, SERNUM: sernum,DESC: desc});
  newphase.save(function(err,newphase){
      if(err)
        return console.error(err);
  })
}

I've tried a bunch of different ways but I get timeout errors or have the assertion be ignored and I can't figure it out.

I feel like the closest I've gotten is

it("throws error when non unique sequence number is used", function(done){    
    (function () {
        ucdphase.createPhase('d0','develop',0,"desc")
    }).should.throw("E11000 duplicate key error index: test.ucdphase.$");

    done();
  });

but what happens then is it prints the error to the console and then says

"AssertionError: expected [Function] to throw an error.
1

There are 1 best solutions below

3
On BEST ANSWER

According chai documentation, you should use expect to start assertion.

Also I don't think you need to use done callback. That callback is used to test asynchronous code.

Try this:

it("throws error when non unique sequence number is used", function(){    
    expect(function () {
        ucdphase.createPhase('d0','develop',0,"desc")
    }).to.throw("E11000 duplicate key error index: test.ucdphase.$");
  });