Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do assertion libraries such as Chai work without forcing a call to a function?

In Chai, you can do stuff like the following:

expect({}).to.exist;

exist is not a function call, but this still works in testing frameworks. The opposite (expect({}).to.not.exist) causes tests to fail, but again, exist is not a function call.

How do these assertions work without making me call a function? In fact, if I try to say expect({}).to.exist() the test fails because exist is not a function.

like image 478
knpwrs Avatar asked Jul 17 '13 23:07

knpwrs


1 Answers

I figured it out (or at least, I figured out a method). Use JavaScript getters:

var throws = {
  get a() {
    throw new Error('a');
  },
  get b() {
    throw new Error('b');
  },
  get c() {
    throw new Error('c');
  }
};

When doing throws.a, throws.b, or throws.c, the appropriate error will be thrown.

From that point it is rather easy to build the assertions which are contained within Chai.

like image 149
knpwrs Avatar answered Sep 29 '22 07:09

knpwrs