简体   繁体   中英

Using Chai expect dynamically

I'm trying to generate mocha tests dynamically, however I'm running into issues:

expect([1, 2, 3])['to']['deep']['equal']([1, 2, 3]);

works fine, however

var e = expect([1, 2, 3]);
e = e['to'];
e = e['deep'];
e = e['equal'];
e([1, 2, 3]);`

produces

Uncaught TypeError: this.assert is not a function at assertEqual (node_modules/chai/lib/chai/core/assertions.js:487:12) at ctx.(anonymous function) (node_modules/chai/lib/chai/utils/addMethod.js:41:25)

on e([1, 2, 3]); . Any idea what is going wrong here or how I would go about fixing this?

JavaScript methods are not bound by default.

var a = {whoAmI: 'a', method: function() {console.log(this);}}
var b = {whoAmI: 'b'};

console.log(a.method()); // will print a

var method = a.method;
method(); // will print the global object (Window)

b.method = method;
b.method(); // will print b

If you need binding you can use closures:

// simple case
var method = function() {return a.method();}
// slightly more complex case, supporting arguments
var method = function() {return a.method.apply(a, arguments);}

method(); // will print a
b.method = method;
b.method(); // will still print a

Or you can use the built-in .bind() method.

var method = a.method.bind(a);

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