2016-05-10 15 views
8

sto riferendo alla libreria di test asserzione: http://chaijs.com/api/bdd/#falseIn che modo Chai JS rende opzionali le parentesi di funzione?

è possibile scrivere affermazioni catena lingua simile al seguente:

expect(false).to.be.false; 

aspettarsi() è ovviamente una funzione globale, "to.be" si presenta come due proprietà, ma come funziona l'ultima parte "false". Mi aspetto che si tratti di una chiamata di funzione:

expect(false).to.be.false(); 

Questa sintassi ES 2015 è? Io non riesco a trovare un riferimento ad esso in https://github.com/lukehoban/es6features

Stack Overflow dice la sua non è possibile: How to implement optional parentheses during function call? (function overloading)

Qualcuno può fare una certa luce su come è implementato qualcosa di simile?

Source Code: https://github.com/chaijs/chai/blob/master/lib/chai/core/assertions.js#L281

+2

Ulteriori informazioni su 'Object.defineProperty' – SLaks

risposta

11

si può fare questo (e un sacco di altre cose) con Object.defineProperty. Ecco un esempio di base:

// our "constructor" takes some value we want to test 
var Test = function (value) { 
    // create our object 
    var testObj = {}; 

    // give it a property called "false" 
    Object.defineProperty(testObj, 'false', { 
     // the "get" function decides what is returned 
     // when the `false` property is retrieved 
     get: function() { 
      return !value; 
     } 
    }); 
    // return our object 
    return testObj; 
}; 

var f1 = Test(false); 
console.log(f1.false); // true 
var f2 = Test("other"); 
console.log(f2.false); // false 

C'è molto di più si può fare con Object.defineProperty. Si dovrebbe verificare the MDN docs for Object.defineProperty per i dettagli.

Problemi correlati