{"id":28795,"date":"2024-04-16T05:09:36","date_gmt":"2024-04-16T04:09:36","guid":{"rendered":"https:\/\/nelkodev.com\/blog\/como-simular-errores-en-llamadas-de-red-para-pruebas-en-javascript\/"},"modified":"2024-06-03T18:44:06","modified_gmt":"2024-06-03T17:44:06","slug":"como-simular-errores-en-llamadas-de-red-para-pruebas-en-javascript","status":"publish","type":"post","link":"https:\/\/nelkodev.com\/en\/blog\/how-to-simulate-errors-in-network-calls-for-testing-in-javascript\/","title":{"rendered":"How to Simulate Errors in Network Calls for Testing in JavaScript"},"content":{"rendered":"<p>In web application development, simulating adverse conditions such as errors in network calls is crucial to ensure the robustness and efficiency of the backend. Here we&#039;ll explore how JavaScript can help us perform these simulations, allowing you to better prepare for real-world scenarios.<\/p>\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_80 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #ffffff;color:#ffffff\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewbox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #ffffff;color:#ffffff\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewbox=\"0 0 24 24\" version=\"1.2\" baseprofile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/nelkodev.com\/en\/blog\/how-to-simulate-errors-in-network-calls-for-testing-in-javascript\/#Entendiendo_la_Importancia_de_las_Simulaciones_de_Error\" >Understanding the Importance of Error Simulations<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/nelkodev.com\/en\/blog\/how-to-simulate-errors-in-network-calls-for-testing-in-javascript\/#Herramientas_y_Estrategias_para_Simular_Errores\" >Tools and Strategies to Simulate Errors<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/nelkodev.com\/en\/blog\/how-to-simulate-errors-in-network-calls-for-testing-in-javascript\/#Uso_de_Fetch_y_Axios_con_Interceptors\" >Using Fetch and Axios with Interceptors<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/nelkodev.com\/en\/blog\/how-to-simulate-errors-in-network-calls-for-testing-in-javascript\/#Simulacion_con_Fetch\" >Simulation with Fetch<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/nelkodev.com\/en\/blog\/how-to-simulate-errors-in-network-calls-for-testing-in-javascript\/#Simulacion_con_Axios_y_Interceptors\" >Simulation with Axios and Interceptors<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/nelkodev.com\/en\/blog\/how-to-simulate-errors-in-network-calls-for-testing-in-javascript\/#Librerias_Especializadas\" >Specialized Bookstores<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/nelkodev.com\/en\/blog\/how-to-simulate-errors-in-network-calls-for-testing-in-javascript\/#Implementando_Pruebas_Automatizadas\" >Implementing Automated Testing<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/nelkodev.com\/en\/blog\/how-to-simulate-errors-in-network-calls-for-testing-in-javascript\/#Ejemplo_de_Prueba_con_Jest\" >Jest Test Example<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/nelkodev.com\/en\/blog\/how-to-simulate-errors-in-network-calls-for-testing-in-javascript\/#Conclusiones\" >Conclusions<\/a><\/li><\/ul><\/nav><\/div>\n<h2><span class=\"ez-toc-section\" id=\"Entendiendo_la_Importancia_de_las_Simulaciones_de_Error\"><\/span>Understanding the Importance of Error Simulations<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>In a production environment, network errors are common. These failures can arise from multiple factors such as server disconnection, slow response times or even programming errors. Correctly simulating these scenarios in the test environment ensures that our application can handle them properly, offering end users a continuous and frustration-free experience.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Herramientas_y_Estrategias_para_Simular_Errores\"><\/span>Tools and Strategies to Simulate Errors<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>JavaScript, with its vast ecosystem, provides various tools and techniques to simulate network errors. We&#039;ll explore some of the most effective methods and how to implement them into your testing process.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Uso_de_Fetch_y_Axios_con_Interceptors\"><\/span>Using Fetch and Axios with Interceptors<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>So much <code>fetch<\/code> as <code>axios<\/code> They are popular for making HTTP requests in JavaScript applications. Both allow requests and responses to be intercepted, which makes them ideal candidates for introducing errors in a controlled manner.<\/p>\n<h4><span class=\"ez-toc-section\" id=\"Simulacion_con_Fetch\"><\/span>Simulation with Fetch<span class=\"ez-toc-section-end\"><\/span><\/h4>\n<p>To simulate an error with <code>fetch<\/code>, we can wrap the call in a function that randomly decides whether to resolve or reject the promise:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">function unreliableFetch(url) { return new Promise((resolve, reject) =&gt; { if (Math.random() &lt; 0.5) { fetch(url) .then(response =&gt; resolve(response)) .catch(error =&gt; reject(error)); } else { reject(new Error(&quot;Simulated network failure&quot;)); }<\/code><\/pre>\n<p>This approach allows us to test how our application handles sudden network failures.<\/p>\n<h4><span class=\"ez-toc-section\" id=\"Simulacion_con_Axios_y_Interceptors\"><\/span>Simulation with Axios and Interceptors<span class=\"ez-toc-section-end\"><\/span><\/h4>\n<p>Axios offers interceptors that you can use to inject errors:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">axios.interceptors.response.use( response =&gt; { return response; }, error =&gt; { if (Math.random() &lt; 0.5) { return Promise.reject(new Error(&quot;Simulated network failure&quot;)); } return Promise.reject(error); } );<\/code><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"Librerias_Especializadas\"><\/span>Specialized Bookstores<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>There are libraries designed specifically for testing that facilitate the simulation of network conditions, such as <code>knock<\/code> for Node.js. <code>knock<\/code> allows you to intercept HTTP\/HTTPS requests from Node and simulate responses of any type.<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">const nock = require(&#039;nock&#039;); nock(&#039;https:\/\/api.miservidor.com&#039;) .get(&#039;\/data&#039;) .reply(500, { error: &quot;Simulated server error&quot; });<\/code><\/pre>\n<p>This tool is extremely powerful for integration testing where controlling server behavior is essential.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Implementando_Pruebas_Automatizadas\"><\/span>Implementing Automated Testing<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Once you have decided on the simulation technique, the next step is to implement automated tests that use these scenarios. Using testing frameworks like Jest or Mocha can make this process easier.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Ejemplo_de_Prueba_con_Jest\"><\/span>Jest Test Example<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Let&#039;s say you have a function that makes a call to an API and processes the response. We could write a Jest test that uses jest-fetch-mock to simulate a failed response:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">import { fetchData } from &#039;.\/api&#039;; jest.mock(&#039;node-fetch&#039;, () =&gt; require(&#039;jest-fetch-mock&#039;).enableMocks()); describe(&#039;Test API call&#039;, () =&gt; { beforeEach(() =&gt; { fetch.resetMocks(); }); test(&#039;handles network error&#039;, async () =&gt; { fetch.mockReject(new Error(&quot;Network error&quot;)); await expect(fetchData()).rejects.toThrow(&quot;Network error&quot;);<\/code><\/pre>\n<h2><span class=\"ez-toc-section\" id=\"Conclusiones\"><\/span>Conclusions<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Simulating network errors during backend testing is critical to building resilient applications. JavaScript and its ecosystem offer multiple tools to facilitate these simulations, helping you prevent problems before they affect your users. Are you ready to strengthen your testing practices? Visit <a href=\"https:\/\/nelkodev.com\/en\/\">NelkoDev<\/a> for more resources or <a href=\"https:\/\/nelkodev.com\/en\/contact\/\">contact me<\/a> If you have questions or need personalized advice.<\/p>","protected":false},"excerpt":{"rendered":"<p>In web application development, simulating adverse conditions such as network call errors is crucial to ensure robustness and efficiency of the backend. Here we will explore how JavaScript can help us perform these simulations, allowing you to better prepare for real-world scenarios. Understanding the Importance of Error Simulations In a web application development, we will explore how JavaScript can help us perform these simulations, allowing you to better prepare for real-world scenarios. Understanding the Importance of Error Simulations In a web application development, we will explore how JavaScript can help us perform these simulations, allowing you to better prepare for real-world scenarios.<\/p>","protected":false},"author":1,"featured_media":28796,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[420,1887,2207],"tags":[38,205,211,1140,62,185,1944,2208,60,1008,1769,1945],"class_list":["post-28795","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blog","category-herramientas-de-desarrollo","category-nodejs","tag-como","tag-blog","tag-desarrollo","tag-errores","tag-herramientas","tag-javascript","tag-llamadas","tag-nodejs","tag-para","tag-pruebas","tag-red","tag-simular"],"_links":{"self":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/28795","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/comments?post=28795"}],"version-history":[{"count":0,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/28795\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media\/28796"}],"wp:attachment":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media?parent=28795"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/categories?post=28795"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/tags?post=28795"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}