React redux async action creator test

2019-08-29 00:53发布

问题:

I am new to the react redux. I am trying to test the async action

action looks like >

export function fetchUserJd() {
  return (dispatch) => {
    let url = FETCH_JD_ROOT_URL + page + "&" + size;
    dispatch({
      type: REQUEST_INITIATED
    })
    get(url)
      .then((response) => {
        if (response.status === 200) {
          dispatch({
            type: REQUEST_SUCCESSED,
          });
          dispatch({
            type: FETCHING_JOBDESCRIPTION_SUCCESS,
            data: response.payload,
          }
          )
        }
        else {
          dispatch({
            type: REQUEST_SUCCESSED
          })
          toastr.error("Error while fetching Job Description, Please check again");
          if (response.status === "") {
            toastr.error('Our server is down. Please check again');
          }
          dispatch({
            type: FETCHING_JOBDESCRIPTION_FAILED,
            data: response.status,
          });
          if (response.status === 401) {
            toastr.error('Please Login Again');
            localStorage.clear();
            history.push('/');
          }
        }
      })
  }

Now I am trying to test it like ,

describe('Header component actions', () => {

    beforeEach(() => moxios.install());
     afterEach(() => moxios.uninstall());

    it('creates Fetch Jopb description when login action is successful', async (done) => {
        let url = FETCH_JD_ROOT_URL + page + "&" + size;
    moxios.stubRequest(url, {
      status: 201,
      response: mockData.jobDescriptionResponse
    });
    const expectedActions = [{ type: "FETCHING_JOBDESCRIPTION_SUCCESS"}];
    const store = mockStore({});
    await store.dispatch(fetchUserJd())
      .then(() => {
        expect(store.getActions()).toEqual(expectedActions);
      });
    done();
  });
});

so here I am getting one error here that is ,

Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

So, I am not getting this error, Can any one help me with this ? And the way I am writing the test case is right ?

To request I also use the token ,

headers: {
                "Authorization": localStorage.getItem("access_token") !== null ? `Bearer ` + localStorage.getItem("access_token") : null,
                "Content-Type": "application/json"
            }

My service for calling is like ,

export const get = (url) =>
    axios.get(
        url,
        {
            headers: {
                "Authorization": localStorage.getItem("access_token") !== null ? `Bearer ` + localStorage.getItem("access_token") : null,
                "Content-Type": "application/json"
            }
        }
    ).then(data => {
        if (data.status === HttpStatus.OK) {
            return {
                status: data.status,
                payload: data.data
            };
        }
    }).catch(err => {
        return {
            status: err.response.data,
            payload: null
        };
    });

So, is it because of I am not passing the tokens ?

回答1:

You forgot to return a Promise from your action creator : you have to return the get call and it should work :

export function fetchUserJd() {
  return (dispatch) => {
    let url = FETCH_JD_ROOT_URL + page + "&" + size;
    dispatch({
      type: REQUEST_INITIATED
    })
    return get(url) // you missed the return statement here
      .then((response) => {
        if (response.status === 200) {
          dispatch({
            type: REQUEST_SUCCESSED,
          });
          dispatch({
            type: FETCHING_JOBDESCRIPTION_SUCCESS,
            data: response.payload,
          }
          )
        }
        else {
          dispatch({
            type: REQUEST_SUCCESSED
          })
          toastr.error("Error while fetching Job Description, Please check again");
          if (response.status === "") {
            toastr.error('Our server is down. Please check again');
          }
          dispatch({
            type: FETCHING_JOBDESCRIPTION_FAILED,
            data: response.status,
          });
          if (response.status === 401) {
            toastr.error('Please Login Again');
            localStorage.clear();
            history.push('/');
          }
        }
      })
  }