0

For code that throws exceptions, I need to wrap the expectation in an anonymous function. Otherwise the exception is thrown before it can be caught by Mocha. See this StackOverflow answer.

But wrapping seems to have side effects.
The following code behaves differently when wrapped. it seems to be a Chai problem.

chai = require 'chai'
expect = chai.expect

describe 'Weird', ->

  obj =
    name: 'kalle'

  it 'not wrapped', () ->
    expect(obj).to.have.property 'name', 'kalle'

  it 'wrapped', () ->
    expect(->obj).to.have.property 'name', 'kalle'

My handcrafted Javascript version:

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

describe('Weird', function() {
    obj = {name: 'kalle'};

    it('not wrapped', function() {
      expect(obj).to.have.property('name', 'kalle');
    });

    it('wrapped', function() {
        expect(function() {return obj}).to.have.property('name', 'kalle');
    });
});

The failure looks like this:
AssertionError: expected [Function] to have a property 'name' of 'kalle', but got ''

Weird
    ✓ not wrapped 
    1) wrapped


  1 passing (10ms)
  1 failing

  1) Weird wrapped:

      + expected - actual

      +kalle

Why does the wrapping yield different results?
Thanks in advance!

Community
  • 1
  • 1
alesch
  • 842
  • 2
  • 8
  • 16

1 Answers1

0

In both cases you are passing the function as a parameter, not the result of the function. I expect that mocha actually calls the function when you call to.throw as is done in the linked SO answer. In order to resolve the function in this situation, you'd want to actually call the function in your expectation:

expect(->obj()).to.have.property 'name', 'kalle'
Jed Schneider
  • 14,085
  • 4
  • 35
  • 46
  • I guess the answeris: when expecting an exception, wrap the function call; otherwise don't. Thanks @Jed for your efforts. – alesch Jan 05 '14 at 14:28