什麼

2017-08-15 43 views
1

我寫了下面的測試「.toMatchObject」和‘objectContaining’之間的區別:什麼

it('Can decrement the current step', function() { 
    expect(reducer(TestState, { type: 'GOTO_PREVIOUS_STEP' })).toMatchObject({ currentStep: 4 }); 
}); 

it('Can decrement the current step v2', function() { 
    expect(reducer(TestState, { type: 'GOTO_PREVIOUS_STEP' })).toEqual(expect.objectContaining({ currentStep: 4 })); 
}); 

他們兩人似乎通過測試,是它們之間有什麼區別嗎?他們之間是否存在績效影響?

回答

1

從查看文檔以及我自己的實驗來確認它,不同之處在於嵌套在作爲期望傳遞的道具中的對象的處理。

如果期望對象具有的屬性,包含一個對象,其中包含一些但不是在實際的物體的等效屬性的屬性,則所有

  • toMatchObject仍將通過, as seen in the docs

  • expect.objectContaining將失敗(除非你聲明屬性的預期目標本身expect.objectContaining())

例子(開玩笑測試):

// objectContaining, with nested object, containing full props/values 
    // PASSES 
    expect({ position: { x: 0, y: 0 } }).toEqual(expect.objectContaining({ 
    position: { 
     x: expect.any(Number), 
     y: expect.any(Number) 
    } 
    })); 

    // objectContaining, with nested object, containing partial props/values 
    // FAILS 
    expect({ position: { x: 0, y: 0 } }).toEqual(expect.objectContaining({ 
    position: { 
     x: expect.any(Number) 
    } 
    })); 

    // objectContaining, with nested object, also declared with objectContaining, containing partial props/values 
    // PASSES 
    expect({ position: { x: 0, y: 0 } }).toEqual(expect.objectContaining({ 
    position: expect.objectContaining({ 
     x: expect.any(Number) 
    }) 
    })); 

    // toMatchObject, with nested object, containing full props/values 
    // PASSES 
    expect({ position: { x: 0, y: 0 } }).toMatchObject({ 
    position: { 
     x: expect.any(Number), 
     y: expect.any(Number) 
    } 
    }); 

    // toMatchObject, with nested object, containing partial props/values 
    // PASSES 
    expect({ position: { x: 0, y: 0 } }).toMatchObject({ 
    position: { 
     x: expect.any(Number) 
    } 
    }); 
1

我的想法是expect.objectContaining(和其他像它這樣的匹配器)可以用來代替傳遞給其他匹配器的「對象」中的文字值。

這個例子是從文檔:

test('onPress gets called with the right thing',() => { 
    const onPress = jest.fn(); 
    simulatePresses(onPress); 
    expect(onPress).toBeCalledWith(expect.objectContaining({ 
    x: expect.any(Number), 
    y: expect.any(Number), 
    })); 
}); 

所以,雖然他們似乎做同樣的事情在你的榜樣,在期望*的人也在這個其他方式有用。