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

130
Views
How to can I initilize state value in unittest to test h2 tag is present in dom or not?

I'm using React v15.4, babel-jest v18 and enzyme v2.5.1

I have a simple React Component:

MyComponent.js

import React, { useState, useEffect, useCallback } from 'react';
import Loader from '../components/Loader';
import axios from 'axios';

const MyComponent = () => {
    const [loading, setLoading] = useState(true);
    const [inputs, setInputs] = useState();

    const getData = useCallback(() => {
        axios.get('http://jsonplaceholder.typicode.com/todos/1')
          .then(res => {
              console.log(res.data)
              setInputs(res.data);
              setLoading(false);
          }).catch(error => {
            console.log(error);
            setLoading(false);
          });
      },[]);
    
      useEffect(() => {
        getData();
      },[getData]);

    return(
        <div>
            <Loader isLoading={loading} />
            {(inputs && !loading) && 
            <>
               <h2>User Information</h2>
               <p>{inputs.id}</p>
               <p>{inputs.userId}</p>
               <p>{inputs.title}</p>
               <p>{inputs.completed}</p>
            </>}
        
        </div>
    );
};
export default MyComponent;

MyComponent.test.js

import  {render} from '@testing-library/react';
import MyComponent from '../components/MyComponent';
import React from "react";
import { configure, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });

test('My Component', () => {
    render(<MyComponent />)
    const widget = mount(<MyComponent />);
    widget.find('h2').text().contains('User Information')
})

The Jest test should pass but I'm getting an error:

Method “text” is only meant to be run on a single node. 0 found instead.

OR how can I initialize state value to test if h2 tag is present in dom or not?

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!