gpt4 book ai didi

reactjs - 使用 redux 和 React 测试异步操作创建器时,无法读取未定义的属性 '.then'

转载 作者:行者123 更新时间:2023-12-03 13:06:40 25 4
gpt4 key购买 nike

我正在尝试使用react、redux-mock-store和redux编写一些测试,但我不断收到错误。也许是因为我的 Promise 尚未得到解决?

当我在开发和生产中尝试时,fetchListing() 操作创建器实际上可以工作,但我在测试通过时遇到了问题。

错误消息

(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)

action/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)
})
})
})

最佳答案

store.dispatch(actions.fetchListings()) 返回未定义。您不能对此调用 .then

参见redux-thunk code 。它执行您返回的函数并返回该函数。您在 fetchListings 中返回的函数不返回任何内容,即 undefined

尝试

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

之后你还会遇到另一个问题。您不会在 then 中返回任何内容,而只需发送。这意味着下一个 then 得到 undefined 参数

关于reactjs - 使用 redux 和 React 测试异步操作创建器时,无法读取未定义的属性 '.then',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44927548/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com