2017-08-15 7 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), 
    })); 
}); 

彼らはあなたの例では、同じことを行うように見える一方で、期待する*ものは、この他の方法でも有用です。

関連する問題