How do I test integration with mock from React?

Asked

Viewed 67 times

1

I want to test the following component but I don’t know how to use jest mocks in case of a request with Axios. Component:

import React, { useEffect, useContext } from 'react'
import { ConfiguracaoPropostaContext } from '../../context'
import { InputCustomizado } from './stylesInputs'
import InputMask from 'react-input-mask'

const Cabecalho = () => {
  const {
    numero,
    bairro,
    cidade,
    cep,
    complemento,
    mudar,
    init
  } = useContext(ConfiguracaoPropostaContext)
  
  useEffect(() => {
    init()
  }, [])
  
  const validationValue = type => {
    return type ? true : false
  }

  return (
    <div className="section-cabecalho">
      <div className="title">
        CABEÇALHO
        <div className="checkbox-desabilitar-cabecalho">
          <input
            type="checkbox"
            onChange={mudarCabecalhoDesabilitado}
            checked={cabecalhoDesabilitado}
          />
          <span>Desabilitar cabeçalho</span>
        </div>
      </div>
      {/* --------- PRECISA SER FEITO UM MAP NESSA REENDERIZAÇÃO --------- */}

        <div className="inputs">
          <div className="input-razao-cnpj">
            <InputCustomizado
              width="15%"
              mRight
              validationValues={validationValue(true)}
            >
              <span>Numero</span>
              <input
                id="input-logradouro-numero"
                name="numero"
                type="text"
                placeholder=""
                value={numero}
                onChange={e => mudar(e)}
              />
            </InputCustomizado>
            <InputCustomizado
              width="35%"
              validationValues={validationValue(true)}
            >
              <span>Bairro</span>
              <input
                id="input-logradouro-bairro"
                name="bairro"
                type="text"
                placeholder=""
                value={bairro}
                onChange={e => mudar(e)}
              />
            </InputCustomizado>
          </div>
          <div className="logradouro2">
            <InputCustomizado
              width="35%"
              mRight
              validationValues={validationValue(true)}
            >
              <span>Cidade</span>
              <input
                id="input-logradouro-cidade"
                name="cidade"
                type="text"
                placeholder=""
                value={cidade}
                onChange={e => mudar(e)}
              />
            </InputCustomizado>
            <InputCustomizado
              width="50%"
              validationValues={validationValue(true)}
            >
              <span>Complemento</span>
              <input
                id="input-logradouro-complemento"
                name="complemento"
                type="text"
                placeholder=""
                value={complemento}
                onChange={e => mudar(e)}
              />
            </InputCustomizado>
          </div>
          <div className="logradouro3">
            <InputCustomizado
              width="28%"
              mRight
              validationValues={validationValue(true)}
            >
              <span>CEP</span>
              <InputMask
                mask="99999-999"
                id="input-logradouro-cep"
                name="cep"
                type="text"
                placeholder=""
                value={cep}
                onChange={e => mudar(e)}
              />
            </InputCustomizado>
            
          </div>
        </div>
      
    </div>
  )
}

export default Cabecalho

My Context Api file:

import React, { useReducer } from 'react'
import modalLoadingStore from '../../../Stores/ModalLoadingStore'
import Api from '../../../Stores/Conexao/conexao'
// import MaquinaDeEstadosContext from '../../../MaquinaDeEstados/context'
import maquinadeestadosstore from '../../../Stores/MaquinaDeEstadosStore'

const initialState = {
  bairro: '',
  cep: '',
  cidade: '',
  complemento: '',
  numero: ''
}

const actions = {
  SET_NUMERO: 'SET_NUMERO',
  SET_BAIRRO: 'SET_BAIRRO',
  SET_CIDADE: 'SET_CIDADE',
  SET_COMPLEMTENTOS: 'SET_COMPLEMTENTOS',
  SET_CEP: 'SET_CEP'
}

const reducer = (state, action) => {
  switch (action.type) {
    case action.type.UPDATE_FIELD:
      return { ...state, [action.payload.name]: action.payload.value }
    case actions.SET_NUMERO:
      return { ...state, numero: action.payload }
    case actions.SET_BAIRRO:
      return { ...state, bairro: action.payload }
    case actions.SET_CIDADE:
      return { ...state, cidade: action.payload }
    case actions.SET_COMPLEMTENTOS:
      return { ...state, complemento: action.payload }
    case actions.SET_CEP:
      return { ...state, cep: action.payload }
    default:
      return state
  }
}

const ConfiguracaoPropostaContext = React.createContext(null)

const Provider = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, initialState)
  // const { setIdEmpresa } = useContext(MaquinaDeEstadosContext)

  const init = async () => {
    modalLoadingStore.handleOpenModal()
    try {
      const proposta = await Api.get(
        `portal/proposta_conf/?fornecedor=${maquinadeestadosstore.getIdEmpresa()}`
      )
      dispatch({
        type: actions.SET_BAIRRO,
        payload: proposta.data.fornecedor.endereco.bairro
      })
      dispatch({
        type: actions.SET_CEP,
        payload: proposta.data.fornecedor.endereco.cep
      })
      dispatch({
        type: actions.SET_CIDADE,
        payload: proposta.data.fornecedor.endereco.cidade
      })
      dispatch({
        type: actions.SET_COMPLEMTENTOS,
        payload: proposta.data.fornecedor.endereco.complemento
      })
      dispatch({
        type: actions.SET_NUMERO,
        payload: proposta.data.fornecedor.endereco.numero
      })
    } catch (err) {
      console.log('err', err)
    } finally {
      modalLoadingStore.handleCloseModal()
    }
  }

  const mudar = e => {
    const { name, value } = e.target
    dispatch({
      type: 'UPDATE_FIELD',
      payload: { name, value }
    })
  }

  const value = {
    ...state,
    mudar,
    init
  }
  return (
    <ConfiguracaoPropostaContext.Provider value={value}>
      {children}
    </ConfiguracaoPropostaContext.Provider>
  )
}

const ConfiguracaoPropostaProvider = Provider

export { ConfiguracaoPropostaContext }
export default ConfiguracaoPropostaProvider

Can anyone help me or offer me some material to do the testing of the component in question? I searched the documentation and videos (mostly in English) and did not find for my specific case.

Thanks in advance.

1 answer

0


Try it this way:

const useContextMock = (React.useContext = jest.fn());
useContextMock.mockReturnValue({ products: mockProducts });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.