Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda