2017-08-11 82 views
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. 
+1

這是一個黑客而不是答案。你可以嘗試expect(''+ obj).toEqual(''+ foo(2))'。它比較函數字符串的內容而不是函數本身。 – Malice

+0

@Malice這並不壞,儘管第二個測試更接近我的用例,我將anon fn分配給了我想要比較的對象中的一個屬性。你的方法可以作爲'.toEqual'中內置的方法來檢查這種類型的相等性 – bitstrider

+0

...但不幸的是,相等性不是完全準確的,因爲'''+ foo(1)===''+ foo (2)「評估爲真」 – bitstrider

回答

2

在這種情況下,無需重寫你的邏輯使用命名功能,你真的不除之外還有其他選擇,例如在測試之前聲明該功能,例如

const foo = i => j => i * j 
const foo2 = foo(2) 
const bar =() => ({ baz: foo2, boz: 1 }) 

describe('Test anonymous function equality',() => { 
    it('+++ bar',() => { 
    const obj = bar() 
    expect(obj).toEqual({ baz: foo2, boz: 1 }) 
    });  
}); 

或者,你檢查obj.bar任何功能,使用expect.any(Function)

expect(obj).toEqual({ baz: expect.any(Function), boz: 1 }) 

這可能會根據測試的情況下實際上更有意義。