Nie można ustawić wartość wybranego elementu wewnątrz komponentu za pomocą enzymu

0

Pytanie

Próbowałem ustawić wartość dla elementu select wewnątrz Dropdown składnik, ale badania nadal daje się zawiesza.

Oto kod polu składnika do testowania.

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);
    });

Wniosek po uruchomieniu 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

Najlepsza odpowiedź

0

Można имитируете onChange, co oznacza, że gdy xyztest spróbuje wywołać onchange, zostanie wykonana funkcja mocked (wartość z rozwijanej listy nie zostanie zmieniona - to jest prawdziwy kod, a nie kod, nad którym znęcają)

Oznacza to, że czekam(akcja) zmiany wartości składnika po wywołaniu zdarzenia "zmiana" (poprzez symulację) źle

Tak, onChange={ onChangeMock } powoduje wykonanie mocked (jest.fn ()) (zamiast "prawdziwego kodu komponentu)

Co właściwie się spodziewać(ation), to to, że przy modelowaniu zdarzenia "zmiana" dla danego składnika (za pomocą kodu wrapper.find('select').simulate('change', { value: 'item2' }); ), a następnie musi być uruchomione zdarzenie onChange, które poprawnie sprawdzane za pomocą kodu expect(onChangeMock.mock.calls.length).toBe(1);

Z małym zastrzeżeniem, nie sprawdzaj zdarzenie "zmiana" - użytkownik nie będzie wykorzystać kod (zdarzenie zmiany), aby wybrać z listy rozwijanej, więc nie należy to sprawdzać. I również nie trzeba testować własną funkcjonalność. Można użyć testy snapshot, jeśli chcesz, aby upewnić się, że po zmianie value z <select>pojawi się nowa wartość. Jednoczesne czytanie: https://kentcdodds.com/blog/testing-implementation-details

2021-12-03 10:53:09

W innych językach

Ta strona jest w innych językach

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