Philipp2706
Philipp2706

Reputation: 39

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;

Upvotes: 0

Views: 603

Answers (1)

Joel Peltonen
Joel Peltonen

Reputation: 13432

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;
}

Upvotes: 1

Related Questions