Student
Student

Reputation: 41

React app testing, how to test an axios post request with Jest?

App.js looks like this, how would I test it with jest?

 

    handleClick = e => {
        axios
          .post(
            "https://api.openweathermap.org/data/2.5/weather?q=" +
              this.state.term +
              "&units=metric&appid=" +
              ApiKey
             
          ){...}

I know I have to create a mocking axios file and then test it like that, but it uses setState in the main App.js. I just want to test the fetch request/axios post with jest.

Upvotes: 1

Views: 1409

Answers (1)

Ramusesan
Ramusesan

Reputation: 904

Just return promise of axios code check below code snippet

    // apiActions.js
    const axios = require('axios');
    
    // your api code goes here
    const fetchData = () => {
      return axios
        .get('https://jsonplaceholder.typicode.com/sample_url')
        .then(response => {
          return response.data;
        });
    };

    exports.fetchData = fetchData;

    // testSuit.js
    import fetchData from './apiActions.js';
    // your testing code goes here
    test('testing api call', () => {
    const sampleObj = {name:'',age:39....}
    fetchData().then(resp => {
      expect(resp).toMatchObject(sampleObj)
    })




        

Upvotes: 0

Related Questions