期望()。to.be.true如何在柴? [英] How does the expect().to.be.true work in Chai?
问题描述
expect(true).to.be.true;
在此代码中,所有'to','be','true'似乎都是来自'expect(true)'的对象响应的属性。
In this code, all the 'to', 'be', 'true' seems to be an attribute of the object response from 'expect(true)'.
这些属性如何工作以便它们可以引发异常?
How can these attributes work so that they can raise an exception?
推荐答案
您可以查看源代码:
[ 'to', 'be', 'been'
, 'is', 'and', 'has', 'have'
, 'with', 'that', 'which', 'at'
, 'of', 'same', 'but', 'does' ].forEach(function (chain) {
Assertion.addProperty(chain);
});
并且 addProperty
in utils
:
https://github.com/chaijs/chai/blob/master/lib/chai/utils/addProperty.js
使用此功能,您可以无限链接属性,如: .to.be.to.to.to.be.equal()
With this you can chain the properties infinitely like: .to.be.to.to.to.be.equal()
让我们创建一个更简单的演示:
Let's create a simpler demonstration:
假设您有一个断言
对象,其中 .true()
method
Assume that you have an assert
object, with the .true()
method
const assert = {
'true': function (v) {
return !!v
}
}
并且您希望能够无限地链接 .to
。只需使用 defineProperty
来定义我们的getter:
and you want to be able to chain .to
infinitely. Simply Use the defineProperty
to define our getter:
Object.defineProperty(assert, 'to', {
get() {
return assert
}
})
所以现在你可以
assert.to.to.to.to.true(false)
工作代码: https://codepen.io/CodinCat/pen/LLzBEX?editors=0012
我在这里添加了另一个更复杂的例子: https://codepen.io/CodinCat/pen/dRVjXL?editors=0012
I've added another more complex example here: https://codepen.io/CodinCat/pen/dRVjXL?editors=0012
在此示例中,您可以看到<中的某些行为code> .true property。
In this example you can see that there is some behaviors in the .true
property.
我们存储来自 expect()$ c $的值c>在内部
__ expectObj
和 __ value
属性中,然后在 .TRUE
。所以你可以
We store the value from expect()
in the internal __expectObj
and the __value
property, and then verify it in the getter of .true
. So you can
expect(false).to.to.to.to.true
这篇关于期望()。to.be.true如何在柴?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!