简体   繁体   中英

Apply Chai chainable getters with an array

I'm not sure how to do the following (or if it's even a smart idea), but I have something like this function:

 testProperty: function(err, data, prop, chaiMethod) { if (Array.isArray(data)) data = data[0]; var propertyValue = (isNaN(parseInt(data.value, 10))) ? data.value : parseInt(data.value, 10); return propertyValue.toString().should[chaiMethod](prop); } }; 

Where chaiMethod is an an array of strings representing the chai string I want to apply. For example:

chiMethod = ['be', 'above']

I'm trying to figure out how to apply these functions to should before I pass in the prop I'm trying to verify.

I think the answer is currying (I'm more than happy to be wrong), and if that's the case, it's a concept I've always had trouble with. Any ideas?

You should be able to just loop over the strings to get the value of each successive property, the final one will hopefully be the function to call:

testProperty: function(err, data, prop, chaiMethod) {

  if (Array.isArray(data)) data = data[0];

    var propertyValue = (isNaN(parseInt(data.value, 10))) ? data.value : parseInt(data.value, 10);

    var assertion = (propertyValue).should,
        fn = assertion;

    for (var i = 0, len = chaiMethod.length - 1; i < len; i++) {
        fn = fn[chaiMethod[i]];
    }
    return fn[chaiMethod[chaiMethod.length-1]](prop);    
  }

};

Also, if you want to do tests like be.above , I don't think they will work if you are converting your propertyValue to a string, so I removed that.

Note I haven't tested any of this, so you'll have to give it a go yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM