我正在使用recordSaga测试模式来测试我的Sagas:
import { runSaga } from "redux-saga";
export default async function recordSaga(saga, initialAction) {
const dispatched = [];
await runSaga(
{
dispatch: action => {
dispatched.push(action);
console.log(dispatched);
}
},
saga,
initialAction
).done;
console.log(dispatched);
return dispatched;
}
describe("getDealsSaga", () => {
it("dispatches a success action with the fetched deals", async () => {
const dispatched = await recordSaga(getDealsSaga, startAction);
console.log(dispatched);
expect(dispatched).toContainEqual(successAction);
});
});
export function* getDealsSaga(): Saga<void> {
try {
const rawDeals: Object[] = yield call(getDealsApi);
const deals: Deal[] = rawDeals.map(p => Deal.fromApi(p));
console.log("getDealsSaga", deals.length, "deals");
yield put({ type: "GET_DEALS_SUCCESS", deals });
} catch (error) {
console.log("getDealsSaga", "error:", error);
yield put({ type: "GET_DEALS_FAILURE", error });
}
}
export default function* dealSaga(): Saga<void> {
yield all([yield takeEvery("GET_DEALS_START", getDealsSaga)]);
}
测试失败,收到一个空数组。但是,传奇中的以及recordSaga
中的日志语句确认传奇正在运行,并且recordSaga
中的回调也正在工作。
console.log recordSaga.js:15
[]
console.log __tests__/dealActions.test.js:46
[]
console.log src/redux/actions/dealActions.js:27
getDealsSaga 10 deals
console.log recordSaga.js:9
[ { type: 'GET_DEALS_SUCCESS',
deals:
[ [Deal],
[Deal],
[Deal],
[Deal],
[Deal],
[Deal],
[Deal],
[Deal],
[Deal],
[Deal] ] } ]
日志的顺序表示recordSaga
或测试中的异步性有问题。
我很困惑,因为我已经将此模式与确切的代码(相同的recordSaga
文件,saga / actions / tests,除了其数据详细信息相同)一起用于其他几个项目中,并且从来没有这个问题。