Não é possível definir o valor do elemento select dentro do componente com a Enzima

0

Pergunta

Eu estive tentando definir o valor de um elemento select dentro do Dropdown componente, mas o teste continua falhando.

Aqui é um codesandbox do componente para testar.

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

Saída após a execução 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

Melhor resposta

0

Você está simulando onChange o que significa que quando o teste de unidade vai tentar chamar onchange, escarnecido, a função de executar (suspenso valor não será alterado - que é o código real não se deixa escarnecer código)

O que significa que o previsto(a) de esperar o componente do valor a mudar quando você chama de "mudança" do evento (através de simular a) está incorreta

Assim, onChange={ onChangeMock } faz com que zombaram (tom de brincadeira.fn()) para ser executado (em vez de componente do "código")

O que é correto esperar(ação) é que quando você simular a "mudança" do evento para o componente (via código wrapper.find('select').simulate('change', { value: 'item2' }); ) e, em seguida, o evento onChange deve ser acionado, o que é validado corretamente através do código expect(onChangeMock.mock.calls.length).toBe(1);

Sobre um pouco tangencial nota, não testar a "mudança" do evento - um usuário não vai usar (código de evento de alteração) para selecionar suspenso valor, então você não deve testar. E você não tem para testar a funcionalidade nativa de ambos. Você pode usar instantâneo testar se você gosta de garantir que, quando você altera value do <select>o novo valor é exibido. Ler relacionado: https://kentcdodds.com/blog/testing-implementation-details

2021-12-03 10:53:09

Em outros idiomas

Esta página está em outros idiomas

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