操作必须是普通对象.使用自定义中间件对测试库执行异步操作,但不使用应用程序



我正在运行一个Create React应用程序,它使用useDispatch来调度redux操作,redux-thunk用于异步网络请求&React测试库。

在我的应用程序上,运行localhost,以下操作正常,但在test/RTL(npm run test(中,它失败,并出现Actions Must Be Plain Objects错误。


// CONTAINER
function MyContainer() {
const [localData, setLocalData] = useState(null);
const dispatch = useDispatch();
const { data, error } = useSelector((state) => state.stocks);
const fetchStuff = async () => {
dispatch(fetchMyDataThunk(process.env.REACT_APP_TOKEN));
};
useEffect(() => {
if (!data) fetchStuff();
setLocalData(data);
}, [data]);
return (
<div data-testid="test-accts-container">
<div className={styles.stockListContainer}>
<p>list of accounts</p>
<AccountsList passDataInHere={localData} />
</div>
</div>
);
}
// THUNK
export const fetchMyDataThunk = (token) => async (dispatch) => {
dispatch(loadMyData());
return Api.fetchStocks(token)
.then((res) => {
dispatch(loadedMyData(res));
return foo;
})
.catch((err) => {
dispatch(loadMyDataFail(err));
return bar;
});
};
// ACTIONS CALLED BY THUNK
export function loadMyData() {
return {
type: constants.LOAD_MY_DATA,
};
}
export function loadedStocksData(data) {
return {
type: constants.LOADED_MY_DATA,
data,
};
}
export function loadStocksFailed(error) {
return {
type: constants.LOAD_MY_DATA_FAIL,
error,
};
}

thunk正在返回返回对象的函数。我不确定我做错了什么?

感谢@phry,它出错的原因是测试utils存储/提供程序中没有中间件。

我完全疏忽了。当我为RTL建立一个新商店时,应该点击。

添加了thunk中间件。

store = createStore(reducer, initialState, applyMiddleware(thunk)),

最新更新