gpt4 book ai didi

reactjs - redux-saga 的单元测试抛出错误 : runSaga must be called on an iterator

转载 作者:行者123 更新时间:2023-12-03 14:18:58 26 4
gpt4 key购买 nike

对于使用 React 和 redux 进行编码以及使用 JEST、enzyme 和 sinon 进行测试,我非常陌生,所以请耐心等待。

我正在尝试在我的应用程序中测试传奇。目前,我正在尝试测试我的“serverSaga”,它负责调用 REST-API 并将状态设置为响应内容(在本例中是食物菜单)。

当我尝试运行测试时,它失败并出现错误:

runSaga must be called on an iterator

20 | describe('Menu View Saga', () => {
21 | it('can retrieve todays menu', async () => {
> 22 | await runSaga(
23 | {
24 | dispatch: action => dispatched.push(action),
25 | getState: () => ({})

我猜这与它无法从 serverSaga 迭代 handleRequest() 中的 yield 有关,但我有点迷失了为什么会这样,以及我做错了什么。

测试:

 import sinon from "sinon";
import * as obj from "../../services/serverService";
import { handleRequest } from '../../sagas/serverSaga'
import { runSaga } from "redux-saga";
import { menuList } from '../../stubs/menuList'
import { setMenu } from '../../reducers/menuReducer'


const serverStub = sinon.stub(obj, 'callServerApi')

serverStub.callsFake(() => {
return {
...menuList.menu
}
})

const saga = handleRequest
const dispatched = {}

describe('Menu View Saga', () => {
it('can retrieve todays menu', async () => {
await runSaga(
{
dispatch: action => dispatched.push(action),
getState: () => ({})
},
saga,
'test-url',
'GET'
).done

expect(serverStub.calledOnce).toBeTruthy()
expect(dispatched).toContainEqual(setMenu(menuList))

})
})

serverSaga

import React, { Component } from 'react'
import { put, call, take, fork, select } from 'redux-saga/effects'
import { callServerApi } from '../services/serverService'


export function* handleRequest(url, method, data){

//TODO - ERROR HANDLING

return yield executeRequest(url, method, data)
}

function* executeRequest(url, method, data) {


try {
let response = yield call(callServerApi, url, method, data)
let responseSuccess = response && response.Succeeded

//temporary workaround - should NOT return response here,
return response



if (responseSuccess) {

yield success(response)
//return response

} else {
console.log('ERROR', response)

//TODO - ERROR HANDLING

} } catch (error){
console.log('Error from serverSaga', error)
//TODO - ERROR HANDLING
}
}

最佳答案

阅读 https://www.npmjs.com/package/redux-saga 上的文档后我意识到我使用的是“非常旧”的 redux-saga 版本(0.10.4)。升级到当前版本 0.16.0 后,它会按预期工作并且错误不再存在。

关于reactjs - redux-saga 的单元测试抛出错误 : runSaga must be called on an iterator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49294236/

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