使用Chai期望动态

时间:2016-06-03 22:01:07

标签: javascript dynamic mocha chai

我试图动态生成mocha测试,但是我遇到了问题:

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

工作正常,但是

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

产生

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)

<{1>} e([1, 2, 3]);。知道这里出了什么问题,或者我将如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

默认情况下,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

如果您需要绑定,可以使用闭包:

// 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

或者您可以使用内置的.bind()方法。

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