Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

210
Visualizações
How to mock socket io response with jest

I am having a hook component that is making calls to the server-side using socket.io. I need to test the functionality of the code. And in order to do that I need to mock the response from socket.io. How to mock the response?

useResult.js

import { useEffect, useRef, useState } from 'react'

import io from 'socket.io-client'

const useResultComponent = () => {
  const socket = useRef()

  // state
  const [loading, setLoading] = useState(false)

  // side effects
  useEffect(() => {
    setLoading(true)

    socket.current = io.connect('', {
      secure: true,
      path: 'url1',
      rejectUnauthorized: true,
      verify: true,
      transports: ['websocket']
    })

    socket.current.on('my_fn_1', function ({ id }) {
      if (id) {
        my_fn_2(id)
      } else {
        setLoading(false)
      }
    })

    socket.current.on('my_fn_3', (res) => {
      setLoading(false)
      if (res.data) {
        socket.current.emit('my_fn_4', { some_data: some_value })
      }
    })
    setTimeout(function () {
      my_fn_1()
    }, 3000)
    // eslint-disable-next-line
  }, [])

  function my_fn_1() {
    socket.current.emit('my_fn_1', params)
  }

  function my_fn_2() {}

  return {
    loading
  }
}
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda