Home > Software engineering >  React async jest not failing as intended
React async jest not failing as intended

Time:03-05

Despite changing the string and the length in my test it always passes. It logs console.log(false) and passes the test.

This is the test

describe('newUsers', done => {
    test('fetches the data from the API and correctly renders it', async () => {
        render(<Input />)
        setTimeout(async () => {
            const items =  await screen.findByPlaceholderText('Search...');
            expect(items).toHaveLength(4);
               done(); 
          }, 100)
          
          //screen.debug()
      })
  })

the call I'm trying to test

const [Loading, setLoading] = useState(false)
  const [name, setName] = useState('');
  const [options, setOptions] = useState([])
  const [data, setData] = useState(false)
  
  useEffect(() => {
    setLoading(true)
    const newUsers = async () => {
        const response = await fetch('https://jsonplaceholder.typicode.com/users')
       .then((res) => res.json())
       .then((data)=> {
         setData(data)
       });
        
    };

    newUsers();
  }, [])

Html

return (
    <div>
    <div className='flex justify-center mt-10'>
        <label>Name</label>
        <input id="input" className='w-96  h-16 border-1 shadow-lg rounded-lg' placeholder="Search..."/>

CodePudding user response:

This happens because the asynchronous code is called after the tests are finished. You can check jest docs for the complete explanation. Basically, to fix it you need to add a done argument in the test function instead of using no arguments. This way, jest will wait until done is called to finish the tests:

describe('newUsers', () => {
  test('fetches the data from the API and correctly renders it', async (done) => {
    render(<Input />)
      setTimeout(async () => {
        const items =  await screen.findByPlaceholderText('Search...');
        expect(items).toHaveLength(4);
        done();
      }, 100)            
    //screen.debug()
  })
})
  • Related