Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

131
Vistas
Cant send AXIOS request from react test

I hope someone can give me a hint with the following problem. I am currently working on the frontend for a REST API. I would like to test if I can submit a POST request.

Using the npm test command, the test runs and shows a green tick for this test function. However, no POST request is sent and thus no entry is written to the database.

The function createObject(json) is called correctly during the test and the JSON string passed is also correct. Unfortunately the AXIOS POST method is not called.

When I click on "Post Object" via the browser the AXIOS method is called and an object is created in the database.

PostClient.js

import axios from 'axios';

const options = {
    headers: {
        // 'Content-Type': 'application/x-www-form-urlencoded'
        'Content-Type': 'application/json',
        'Accept': 'application/json',
    } };

export class PostClient {

        // This function is called by the test, but the Axios command is not.
        static createObject(json) {

        const response = axios.post('http://localhost:8080/object/create/', JSON.stringify(json), options)
            .then(response => {
                console.log(response.data);
                return response;
            }).catch(function (error) {
                console.log(error);
            });
            return response;
    }  

}

App.test.js

describe('Test', function(){
   
  let id;         

  it('addObject()', function () {
    
    const response = PostClient.createObject(objectJSON);
    this.id = response.id;

    expect(response.status == 200);

  });
});

App.js

class App extends React.Component {
 
  render() {
    return (
      <>
        <h2>createObject</h2>
        <div className="createObject">
          <button onClick={() => PostClient.createObject(objectJSON)}>Post Object</button>
        </div>
       ...
      </>
    );
  }
}

export default App;
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

First: read the comment by Yevgen Gorbunkov :)

Second: axios.post() method returns a Promise - you are returning that promise instead of returning the result of your request.

My advice is to review how promises work; MDN has a nice article - and maybe brush up on asynchronous code in general.

The quick and dirty solution might be to turn your function into an async function and use async/await:

static async createObject(json) {
    // Note: this might throw an error; try...catch is a good idea
    const response = await axios.post(url, payload, options);
    return response.data;
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda