Как с помощью Jest и Enzyme протестировать обработчик пользовательской формы? - PullRequest
0 голосов
/ 11 июля 2020

Я новичок в тестировании автоматизации, поэтому я пытаюсь выполнить несколько модульных тестов, я построил обычный пользовательский хук для обработки событий формы и изменений входных данных.

import { useState } from 'react'

const useFormHook = (callback) => {

    const [inputs, setInputs] = useState({});

    const handleSubmit = (e) => {
        if (e) {
           e.preventDefault();
        }
        setInputs({})
        callback();
      }

    const handleInputChange = (e) => {
         e.persist();
         setInputs(inputs => ( {...inputs, [e.target.name]: e.target.value } ));
    }

    return{
       handleSubmit,
       handleInputChange,
       inputs
    }
}

export default useFormHook

и реализация переходит в панель поиска, и это событие обновляет состояние контекста и выглядит так:

const SearchBar = () => {

    const [search, setSearch] = useState('')

    useAsyncHook(search); // I'm using an async custom hook to fetch some data with axios. 

    const handleFormSubmit = () => {
        
             let targetValue = Object.values(inputs).join().toLowerCase()

             setSearch(targetValue)
                         
             document.forms[0].reset()
    }

    const { inputs, handleSubmit, handleInputChange } = useCustomFormHook(handleFormSubmit)

     return (
        
        <form onSubmit={handleSubmit} className="searchForm">
             <input 
                id='searchBar'
                type="text" 
                name="value" 
                value={inputs.value || ''}
                onChange={handleInputChange} 
                required
                className={`input`}
             />
            <input 
               className={`button primary`} 
               type="submit" 
               value="? Search" 
               id='search-button'
            /> 
        
       </form>
       
    )
}

до сих пор все работает нормально ..:

import React from "react";
import { mount, shallow } from "enzyme";
//components and hooks
import useFormHook from "../../../Services/Hooks/customFormHook";
//import useAsyncHook from "../../../Services/Hooks/customAsyncHook";
//import SeachBar from "../SearchBar";

describe("Custom hooks suite test", () => {
  // const wrapper = shallow(<SeachBar />);

  let results;

  const handleHookTester = (hook) => {
    function HookWrapper() {
      results = hook();
      return null;
    }
    mount(<HookWrapper />);
    return results;
  };

  it("Form hook test", () => {
    handleHookTester(useFormHook);
    expect(results.inputs).toStrictEqual({});
  });
});

Пока что я ' мне удалось заставить его работать, но это всего лишь customFormHook, и я хотел бы протестировать, и мой customAsyncHook, который выглядит так:

const useAsyncHook = (id) => {

    const [loading, setLoading] = useState('false');

    const { findData } = useContext(AppContext) 
// 1 -  
     useEffect(() => {
    
      async function getData() {
     
        try {
           setLoading('true'); 
          
           const response = await axios(
             `someEndPoint/${id}`
           );

           findData({type:FIND_DATA, data:response.data }); 

        } catch (error) {
          
           setLoading('null'); 
           findData({type:FIND_DATA, data:null }); 
        }

      }
       
      if (id !== "") {
         getData();
      }

    }, [id]);
     
    return  loading; 

  }

и если я попробую что-то вроде const wrapper = shallow(<SearchBar/>) или: handleHookTester(useAsyncHook); тест не проходит, выдает следующую ошибку:

 ● Custom hooks suite test › encountered a declaration exception

    TypeError: Cannot destructure property 'findData' of '(0 , _react.useContext)(...)' as it is undefined.

       8 |     const [loading, setLoading] = useState('false');
       9 | 
    > 10 |     const { findData } = useContext(AppContext) 
         |             ^
      11 | // 1 -  
      12 |      useEffect(() => {

Итак, вопрос в том, должен ли я имитировать эту функцию? а как?

...