0

var checkBox = document.getElementById("myCheck");
var checkBoxChecked = "false";
if (checkBox.checked == true){
  checkBoxChecked = "true";
}
const uri = 'https://jsonplaceholder.typicode.com/posts?exact' + checkBoxChecked;
    const initDetails = {
        method: 'get',
        headers: {
            "Content-Type": "application/json; charset=utf-8"
        },
        mode: "cors"
    }
    
    function getData() {
        fetch(uri, initDetails)
        .then(response => {
            if (response.status !== 200) {
                console.log('Looks like there was a problem. Status Code: ' +
                response.status);
                return;
            }
    
            console.log(response.headers.get("Content-Type"));
            return response.json();
            }
        )
        .then(myJson => {
            console.log(JSON.stringify(myJson));
        })
        .catch(err => {
            console.log('Fetch Error :-S', err);
        });
    }
    
    window.onload=function() {
        let myButton = document.getElementById("getData");
        myButton.addEventListener('click', getData);
    }
<!DOCTYPE html>
<html>
<body>

<h2>HTML Forms</h2>

<form action="/action_page.php">
  <label for="fname">Search:</label><br>
  <input type="text" id="fname" name="fname" value="John">
    <input type="radio" id="myCheck" name="fav_language" value="HTML">
  <label for="html">Exact</label><br><br>
  <input type="submit" id="getData" value="Submit">
</form> 
<script>

</script>

</body>
</html>
  • I have one text box and radio button name is exact
  • Onsubmit i call fetch api.
  • I need to check fetch api request url have exact query parameter
  • if exact parameter is not added in request fetch api call it will be error.
  • if exact parameter not added in fetch api request i need to throw error in rtl test case.

URL: https://jsonplaceholder.typicode.com/posts?exact=true

EX: expect(fetch.url()).toContain('?exact=true');

1 Answers1

0

import { render } from '@testing-library/react';

test('fetches data from the correct URL', async () => {
  const fetchMock = jest.spyOn(global, 'fetch');
  
  render(<MyComponent />);
  
  expect(fetchMock).toHaveBeenCalledWith('https://example.com/data');
});