Enzim içeren bileşen içindeki select öğesinin değeri ayarlanamıyor

0

Soru

İçindeki bir select öğesinin değerini ayarlamaya çalışıyorum. Dropdown bileşen, ancak test başarısız olmaya devam ediyor.

İşte test edilecek bileşenin bir codesandbox'ı.

it('should execute onChange once and change value to "item2"', () => {
        const onChangeMock = jest.fn();
        const wrapper = mount(
            <Dropdown{ ...args } 
                onChange={ onChangeMock } 
                listItems={ ['item1', 'item2', 'item3'] } />
        );

    
        wrapper.find('select').simulate('change', { value: 'item2' });

        console.log(wrapper.debug());
        console.log(wrapper.find('select').props());
        
        expect(wrapper.find('select').props().value).toBe('item2');
        expect(onChangeMock.mock.calls.length).toBe(1);
    });

Çalıştırdıktan sonra çıktı npm run test:

 expect(received).toBe(expected) // Object.is equality
 Expected: "item2"
 Received: undefined

 51 |         console.log(wrapper.find('select').props());
 52 |         
 53 |         expect(wrapper.find('select').props().value).toBe('item2');
    |                                                      ^
 54 |         expect(onChangeMock.mock.calls.length).toBe(1);
 55 |     });
 56 | });
console.log
    <Dropdown id="" name="" label="" placeholder="" errorMessage="" valid={false} required={false} listItems={{...}} onChange={[Function: mockConstructor] { _isMockFunction: true, getMockImplementation: [Function (anonymous)], mock: Object [Object: null prototype] { calls: [ [ SyntheticBaseEvent { _reactName: 'onChange', _targetInst: [Object], type: 'change', nativeEvent: [Object], target: [Object], currentTarget: null, eventPhase: undefined, bubbles: undefined, cancelable: undefined, timeStamp: 1637655017281, defaultPrevented: undefined, isTrusted: undefined, isDefaultPrevented: [Function: functionThatReturnsFalse], isPropagationStopped: [Function: functionThatReturnsFalse], value: 'item2', _dispatchListeners: null, _dispatchInstances: null } ] ], instances: [ undefined ], invocationCallOrder: [ 1 ], results: [ Object [Object: null prototype] { type: 'return', value: undefined } ] }, mockClear: [Function (anonymous)], mockReset: [Function (anonymous)], mockRestore: [Function (anonymous)], mockReturnValueOnce: [Function (anonymous)], mockResolvedValueOnce: [Function (anonymous)], mockRejectedValueOnce: [Function (anonymous)], mockReturnValue: [Function (anonymous)], mockResolvedValue: [Function (anonymous)], mockRejectedValue: [Function (anonymous)], mockImplementationOnce: [Function (anonymous)], mockImplementation: [Function (anonymous)], mockReturnThis: [Function (anonymous)], mockName: [Function (anonymous)], getMockName: [Function (anonymous)] }}>
      <div className="med-dropdown">
        <label htmlFor="" className="med-dropdown__label">
           (Optional)
        </label>
        <select id="" name="" className="med-dropdown__select false" defaultValue={0} onChange={[Function: mockConstructor] { _isMockFunction: true, getMockImplementation: [Function (anonymous)], mock: Object [Object: null prototype] { calls: [ [ SyntheticBaseEvent { _reactName: 'onChange', _targetInst: [Object], type: 'change', nativeEvent: [Object], target: [Object], currentTarget: null, eventPhase: undefined, bubbles: undefined, cancelable: undefined, timeStamp: 1637655017281, defaultPrevented: undefined, isTrusted: undefined, isDefaultPrevented: [Function: functionThatReturnsFalse], isPropagationStopped: [Function: functionThatReturnsFalse], value: 'item2', _dispatchListeners: null, _dispatchInstances: null } ] ], instances: [ undefined ], invocationCallOrder: [ 1 ], results: [ Object [Object: null prototype] { type: 'return', value: undefined } ] }, mockClear: [Function (anonymous)], mockReset: [Function (anonymous)], mockRestore: [Function (anonymous)], mockReturnValueOnce: [Function (anonymous)], mockResolvedValueOnce: [Function (anonymous)], mockRejectedValueOnce: [Function (anonymous)], mockReturnValue: [Function (anonymous)], mockResolvedValue: [Function (anonymous)], mockRejectedValue: [Function (anonymous)], mockImplementationOnce: [Function (anonymous)], mockImplementation: [Function (anonymous)], mockReturnThis: [Function (anonymous)], mockName: [Function (anonymous)], getMockName: [Function (anonymous)] }} onFocus={[Function: onFocus]} onBlur={[Function: onBlur]} disabled={[undefined]}>
          <option disabled={true} value={0} />
          <option value="item1">
            item1
          </option>
          <option value="item2">
            item2
          </option>
          <option value="item3">
            item3
          </option>
        </select>
      </div>
    </Dropdown>
enzyme jestjs reactjs
2021-11-23 08:17:33
1

En iyi cevabı

0

Onchange'i simüle ediyorsunuz, yani birim testi onchange'i çağırmaya çalıştığında, mocked işlevi yürütülecek (açılır değer değiştirilmeyecek - bu gerçek kod, mocked kodu değil)

Bu, "değiştir" olayını (simulate aracılığıyla) çağırdığınızda bileşenin değerinin değişmesini beklemenin(ation) yanlış olduğu anlamına gelir

Böyle, onChange={ onChangeMock } alay edilmesine neden olur (şaka.yürütülecek fn ()) (bileşenin "gerçek kodu" yerine)

Ne doğru bekliyoruz(listesine alınmıştır) olduğu zaman sizi taklit bu "değişim" olay parça (kod aracılığıyla wrapper.find('select').simulate('change', { value: 'item2' }); ), daha sonra kod aracılığıyla doğru bir şekilde doğrulanan onChange olayı tetiklenmelidir expect(onChangeMock.mock.calls.length).toBe(1);

Biraz teğetsel bir notta, "değiştir" olayını test etmeyin-bir kullanıcı açılır menü değerini seçmek için kodu (olayı değiştir) kullanmaz, bu nedenle bunu test etmemelisiniz. Ve yerel işlevselliği de test etmeniz gerekmez. Değişiklik yaptığınızda emin olmak isterseniz anlık görüntü testini kullanabilirsiniz value of the <select>, yeni değer görüntülenir. İlgili okuma: https://kentcdodds.com/blog/testing-implementation-details

2021-12-03 10:53:09

Diğer dillerde

Bu sayfa diğer dillerde

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................