[英]Automated testing with chai js
I want to load a configuration file for tests. 我想加载配置文件进行测试。
One of the parameters is type. 参数之一是类型。
So how can I replace the next line. 那么我该如何替换下一行。
expect(res.body).to.deep.equal(test.expect
) expect(res.body).to.deep.equal(test.expect
)
with "to.deep.equal" string. 与“ to.deep.equal”字符串。
I tried : 我试过了 :
let exp = expect(res.body);
test.type.split('.').forEach(t => exp = exp[t])
exp(test.expect)
But then i got: 但是后来我得到了:
Uncaught TypeError: this.assert is not a function
at assertEqual (node_modules\chai\lib\chai\core\assertions.js:1026:12)
EDIT: 编辑:
I managed to do it in the following way: 我设法通过以下方式做到这一点:
let exp = expect(res.body);
test.type.split('.').slice(0,-1).forEach(t => exp = exp[t])
exp[_.last(test.type.split('.'))](test.expect)
I'd love to get an explanation for that. 我很乐意对此进行解释。 and if is exist another way for it.
是否存在另一种方法。
Because you're breaking the thisValue of the last member ( equal
), which it tries to access but is no longer bound to deep
object. 因为您正在破坏最后一个成员(
equal
)的thisValue ,它试图访问该成员但不再绑定到deep
对象。
(I'm really butchering the explanation). (我真的在解释这个问题)。
You can do: 你可以做:
let exp = expect(res.body);
test.type.split('.').forEach(t => {
exp = typeof exp[t] === 'function'
? exp[t].bind(exp)
: exp[t];
});
exp(test.expect)
To further explain, this is why you're seeing the TypeError: this.assert is not a function
- the equal
call is trying to access this.assert
of the deep
object, but the this
is no longer bound to it. 为了进一步说明,这就是为什么您看到
TypeError: this.assert is not a function
- equal
调用试图访问deep
对象的this.assert
,但是this
不再绑定到它。 By explicitly binding it via .bind()
we can retain it. 通过
.bind()
显式绑定它,我们可以保留它。
That's also why your second code example works, because you're properly calling the equal()
as a method of deep
. 这就是为什么第二个代码示例起作用的原因,因为您正在正确地将
equal()
调用为deep
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.