Подтвердить что ты не робот

Невозможно прочитать свойство ".then" из undefined при тестировании создателей асинхронного действия с помощью сокращения и реакции

Я пытаюсь написать какой-нибудь тест, использующий реагирование, redux-mock-store и redux, но я продолжаю получать ошибки. Может быть, потому что мое Promise еще не выполнено?

Создатель действия fetchListing() фактически работает, когда я пробую его на dev и production, но у меня возникают проблемы при прохождении теста.

сообщение об ошибке

(node:19143) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 3): SyntaxError
(node:19143) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
 FAIL  src/actions/__tests__/action.test.js
  ● async actions › creates "FETCH_LISTINGS" when fetching listing has been done

    TypeError: Cannot read property 'then' of undefined

      at Object.<anonymous> (src/actions/__tests__/action.test.js:44:51)
          at Promise (<anonymous>)
      at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)
          at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:169:7)

  async actions
    ✕ creates "FETCH_LISTINGS" when fetching listing has been done (10ms)

Действие /index.js

// actions/index.js
import axios from 'axios';

import { FETCH_LISTINGS } from './types';

export function fetchListings() {

  const request = axios.get('/5/index.cfm?event=stream:listings');

  return (dispatch) => {
    request.then(( { data } ) => {
      dispatch({ type: FETCH_LISTINGS, payload: data });
    });
  }
};

action.test.js

// actions/__test__/action.test.js

import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { applyMiddleware } from 'redux';
import nock from 'nock';
import expect from 'expect';

import * as actions from '../index';
import * as types from '../types';


const middlewares = [ thunk ];
const mockStore = configureMockStore(middlewares);

describe('async actions', () => {
  afterEach(() => {
    nock.cleanAll()
})


it('creates "FETCH_LISTINGS" when fetching listing has been done', () => {
  nock('http://example.com/')
    .get('/listings')
    .reply(200, { body: { listings: [{ 'corpo_id': 5629, id: 1382796, name: 'masm' }] } })

    const expectedActions = [
      { type: types.FETCH_LISTINGS }, { body: { listings: [{ 'corpo_id': 5629, id: 1382796, name: 'masm' }] }}
    ]

    const store = mockStore({ listings: [] })

    return store.dispatch(actions.fetchListings()).then((data) => {
      expect(store.getActions()).toEqual(expectedActions)
    })
  })
})
4b9b3361

Ответ 1

store.dispatch(actions.fetchListings()) возвращает undefined. Вы не можете позвонить. .then по этому вопросу.

Смотрите редукционный код. Он выполняет возвращаемую функцию и возвращает ее. Функция, которую вы возвращаете в fetchListings ничего не возвращает, т.е. undefined.

Пытаться

return (dispatch) => {
    return request.then( (data) => {
      dispatch({ type: FETCH_LISTINGS, payload: data });
    });
  }

После этого у вас все еще будет другая проблема. Вы ничего не возвращает внутри then, вы только отправка. Это означает, что следующий then получает undefined аргумент

Ответ 2

Я также знаю, что это старый поток, но вам нужно убедиться, что вы возвращаете асинхронное действие внутри своего thunk.

В моем Thunk мне нужно было:

return fetch()

асинхронное действие, и это сработало

Ответ 3

Я знаю, что это старый поток. Но я думаю, что проблема заключается в том, что ваш создатель действия не является асинхронным.

Try:

export async function fetchListings() {
  const request = axios.get('/5/index.cfm?event=stream:listings');
  return (dispatch) => {
    request.then(( { data } ) => {
      dispatch({ type: FETCH_LISTINGS, payload: data });
    });
  }
}

Ответ 4

Создатель вашего действия должен вернуть обещание, как показано ниже:

// actions/index.js
import axios from 'axios';

import { FETCH_LISTINGS } from './types';

export function fetchListings() {
  return (dispatch) => {
    return axios.get('/5/index.cfm?event=stream:listings')
    .then(( { data } ) => {
      dispatch({ type: FETCH_LISTINGS, payload: data });
    });
  }
};