[英]Using Chai expect dynamically
I'm trying to generate mocha tests dynamically, however I'm running into issues: 我正在尝试动态生成mocha测试,但是我遇到了问题:
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]);
在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. 默认情况下,JavaScript方法不受约束。
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. 或者您可以使用内置的.bind()
方法。
var method = a.method.bind(a);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.