1

In the following script only one test is passing. Testing error (throw Error()) is failing with message 1) a test should throw error:

var expect = require('chai').expect;
describe("a test", function() {
    var fn;
    before(function() {
        fn = function(arg){
            if(arg == 'error'){
                throw new Error();
            }else{
                return 'hi';
            } 
        }
    });

    it("should throw error", function() {
        expect(fn('error')).to.throw(Error);
    });
    it("should return hi", function() {
        expect(fn('hi')).to.equal('hi');
    });
});

How to alter expect to test errors?

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
Ordre Nln
  • 157
  • 3
  • 11

2 Answers2

3

expect() needs a function to call, not the result of the function.

Change your code to:

expect(function(){ fn("error"); }).to.throw(Error);
juunas
  • 54,244
  • 13
  • 113
  • 149
  • No, the documentation is correct. The point is you must pass in a function object that Chai will call. In your example, you are calling the function, and passing the result to `expect()`. – juunas Feb 17 '15 at 15:34
  • then why expect(fn('hi')).to.equal('hi'); works? – Ordre Nln Feb 17 '15 at 16:55
  • Because, in that case, you run the function and return "hi". You then pass the string to expect(), and ask if it equals the other string. In the case of testing for thrown errors, this cannot be done, as expect has no way of catching the error unless it calls it. – juunas Feb 18 '15 at 00:54
  • Could you also accept my answer if it works for you now? – juunas Feb 18 '15 at 02:14
  • this applies to [should](http://shouldjs.github.io/#assertion-throw) as well. read the docs carefully and understand the difference between a function and the return value of a function call – smoebody Apr 10 '15 at 10:31
0

If you do it the Node way with error first callbacks, it would look more like this:

var expect = require('chai').expect;

describe("a test", function() {
  var fn;
  before(function() {
    fn = function(err, callback){
        if(err) throw new Error('failure');

        return callback();
    }
  });

  it("should throw error", function() {
    expect(fn('error')).to.throw(Error);
  });
  it("should return hi", function() {
    var callback = function() { return 'hi' };
    expect(fn(null, callback).to.equal('hi');
  });
});
sctskw
  • 1,588
  • 1
  • 12
  • 14
  • Did you try your code? Your expect will fail. Like I said in my answer, it needs a function to call, not the result of the function. – juunas Feb 17 '15 at 15:43