Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Identifying component and DOM for testing library React

I have a component named Student

        function Student(props){
         const {gradeDetails,addressDetails}=props;
         const [marksData,setMarksData]=useState(null);
   

  function fetchMarksData()
       {
        let url=/api/getMarks/+studentID
        axios
            .get(url)
            .then(output=> {
                              setMarksData(output.data); 
                           }
        }
        return ( 
                  <div>
                      <label>{addressDetails.cityName}</label>
                      <label>{marksData.marks}</label>
                      <render other details here>
                  </div>)
    }
    export default Student;

I have created a test as follows

test('Make sure student component renders for City testCity',()=>{
   render(<Student gradeDetails={grdDetails} addressDetails={addDetails}/>);
   const cityExists = screen.findByDisplayValue(/testCity/i);
   expect(cityExists).toBeInTheDocument();

My Questions are:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. How to see the rendered DOM (HTML) to make sure the component is rendered successfully?
  2. Student component also has a axios API call "getMarks()". Do I need to mock that API also so that Student component will be rendered ? How to do that?
  3. When I call expect(cityExists).toBeInTheDocument();, I am getting error message "Received has value {}" so i suspect that the component is not rendered successfully. In that case I need to see the HTML.

Please suggest….

>Solution :

You can use debug to see the DOM

const { debug } = render(<Student gradeDetails={grdDetails} addressDetails={addDetails}/>);

debug()

Yes you need to mock the API. MSW is the best way of doing this https://mswjs.io/docs/getting-started/integrate/node#using-manual-setup. Here is a nice guide: https://www.stackbuilders.com/blog/testing-react-components-with-testing-library-and-mock-service-worker/

Once setup in jest you can just do this in a beforeAll:

  rest.get('/api/getMarks/:studentID', (req, res, ctx) => {
    return res(ctx.json({  })) // PUT MOCKED DATA INSIDE THE OBJECT
  })

The third question I can’t answer as I cant see where testCity appears in your component.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading