gpt4 book ai didi

javascript - 动态使用 Chai Expect

转载 作者:行者123 更新时间:2023-11-28 05:56:29 25 4
gpt4 key购买 nike

我正在尝试动态生成 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]);`

产生

未捕获类型错误:this.assert 不是函数
在assertEqual (node_modules/chai/lib/chai/core/assertions.js:487:12)
在 ctx.(匿名函数)(node_modules/chai/lib/chai/utils/addMethod.js:41:25)

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

最佳答案

默认情况下不绑定(bind) 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

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

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

关于javascript - 动态使用 Chai Expect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37624081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com