4
有沒有辦法用[email protected]
來測試匿名函數的相等性?使用Jest測試匿名函數的相等性
我試圖通過類似的測試:
const foo = i => j => {return i*j}
const bar =() => {baz:foo(2), boz:1}
describe('Test anonymous function equality',()=>{
it('+++ foo',() => {
const obj = foo(2)
expect(obj).toBe(foo(2))
});
it('+++ bar',() => {
const obj = bar()
expect(obj).toEqual({baz:foo(2), boz:1})
});
});
目前產生:
● >>>Test anonymous function equality › +++ foo
expect(received).toBe(expected)
Expected value to be (using ===):
[Function anonymous]
Received:
[Function anonymous]
Difference:
Compared values have no visual difference.
● >>>Test anonymous function equality › +++ bar
expect(received).toBe(expected)
Expected value to be (using ===):
{baz: [Function anonymous], boz:1}
Received:
{baz: [Function anonymous], boz:1}
Difference:
Compared values have no visual difference.
這是一個黑客而不是答案。你可以嘗試expect(''+ obj).toEqual(''+ foo(2))'。它比較函數字符串的內容而不是函數本身。 – Malice
@Malice這並不壞,儘管第二個測試更接近我的用例,我將anon fn分配給了我想要比較的對象中的一個屬性。你的方法可以作爲'.toEqual'中內置的方法來檢查這種類型的相等性 – bitstrider
...但不幸的是,相等性不是完全準確的,因爲'''+ foo(1)===''+ foo (2)「評估爲真」 – bitstrider