簡體   English   中英

使用Chai期望動態

[英]Using Chai expect dynamically

我正在嘗試動態生成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)

e([1, 2, 3]); 知道這里出了什么問題,或者我將如何解決這個問題?

默認情況下,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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM