mercredi 15 mars 2017

How to test React function that has api request in it?

I have a function like so in a react component. How do I test a successful request and an unsuccessful request?

deleteQuestion(id) {
  axios.delete('/api/questions/' + id)
    .then(response => {
      this.setState({message: "Deletion Successful!"});
    }).catch(error => {
      var errorMessage = 'Question not deleted: ' + error.response.data.message;
      this.setState({error: errorMessage});
    });
}

And I was thinking of doing something like this for the testing but this obviously does not work. As I do not now how to make it send a successful request.

import React from 'react';
import { mount, shallow } from 'enzyme';
import axios from 'axios';
import QuestionList from './QuestionList';
import sinon from 'sinon';

it('deleteQuestion', () => {
  const wrapper = renderComponent();
  wrapper.instance().deleteQuestion(2)
  expect(wrapper.state().message).to.equal('Deletion Successful!');

});

Aucun commentaire:

Enregistrer un commentaire