Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

197
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!