Code Generator | JavaScript

fetchData - Fetches data from an API endpoint

This JavaScript code snippet provides a function named `fetchData` that fetches data from the specified API endpoint using the `fetch` method. The function takes a URL as a parameter and returns a Promise that resolves to the fetched data. If an


Empty image or helper icon

This Query related with thread "Deep Dive into Firebase Query Optimization"

Prompt

create fetch function for api with unit test

Answer

JavaScript code snippet:

/**
 * Fetches data from the specified API endpoint
 * @param {string} url - The URL of the API endpoint
 * @returns {Promise} - A Promise that resolves to the fetched data
 */
function fetchData(url) {
  return fetch(url)
    .then(response => response.json())
    .catch(error => {
      console.error('Error fetching data:', error);
      throw new Error('Failed to fetch data');
    });
}

/**
 * Unit test for fetchData function
 */
function testFetchData() {
  // Mock API endpoint
  const url = 'https://api.example.com/data';
  
  // Call fetchData function
  fetchData(url)
    .then(data => {
      // Assert that data is fetched successfully
      console.log('Data fetched successfully:', data);
    })
    .catch(error => {
      // Handle any errors
      console.error('Failed to fetch data:', error);
    });
}

Example usage:

// Call the fetchData function with the API endpoint URL
fetchData('https://api.example.com/data')
  .then(data => {
    // Process the fetched data
    console.log('Data:', data);
  })
  .catch(error => {
    // Handle any errors
    console.error('Error:', error);
  });

Unit testing:

To test the fetchData function, call the testFetchData function. The function mocks an API endpoint and verifies that the data is fetched successfully.

testFetchData();

Note: Make sure to replace the URL with the appropriate API endpoint for your specific use case.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

This JavaScript code snippet provides a function named fetchData that fetches data from the specified API endpoint using the fetch method. The function takes a URL as a parameter and returns a Promise that resolves to the fetched data. If an error occurs, it logs the error message and throws an error. The code also includes a unit test function, testFetchData, which mocks an API endpoint and verifies that the data is fetched successfully. An example usage of the fetchData function is provided, along with instructions for unit testing.