Identifying component and DOM for testing library React

Advertisements

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:

  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.

Leave a Reply Cancel reply