RTK Query中onQueryStarted使用await无效,测试需额外sleep
问题原因及解决方案
核心问题:子API请求未被正确等待
你在onQueryStarted中调用其他RTK Query endpoint的方式有误,导致await dispatch(setCurrentScenario.initiate(1))并没有真正等待所有子API请求完成,测试时自然无法立即获取到更新后的状态。
具体来说,api.endpoints.milestones.initiate({theid: id})(dispatch, getState, "api")这种写法是错误的:
initiate()返回的是一个thunk action creator,必须通过dispatch()来执行,且dispatch(thunk)才会返回对应API请求完成的Promise。- 你直接调用action函数的方式,虽然能触发请求,但返回的Promise无法正确反映请求的完成状态,导致
await ml和await pg并没有等待请求结束就继续执行后续代码,onQueryStarted提前完成,dispatch(setCurrentScenario.initiate(...))的Promise也提前resolve,但此时子请求的状态更新还没完成。
修正后的代码
修改setCurrentScenario的onQueryStarted方法,正确等待子请求完成:
setCurrentScenario: builder.query({ query: id => `scenarios/${id}`, async onQueryStarted (id, { dispatch, queryFulfilled, getState }) { try { // 正确方式:通过dispatch执行initiate返回的thunk,并await其完成 const mlResult = await dispatch(api.endpoints.milestones.initiate({theid: id})); const pgResult = await dispatch(api.endpoints.groups.initiate({theid: id})); const currentScen = await queryFulfilled; dispatch( scenarioActions.addCurrentScenario( currentScen.data )); dispatch( scenarioActions.addCurrentScenarioMilestones( mlResult.data )); dispatch( scenarioActions.addCurrentScenarioPlayerGroups( pgResult.data )); } catch (error) { console.log('ERRORE IN SETCURRENTSCENARIO: ', error); } } })
测试代码调整
修正后,测试中无需再使用sleep,直接await dispatch后即可获取更新后的状态:
describe('A single Scenario should be fetched if user is manager', () => { it('should populate `current` scenario after asking with its `id`', async () => { await store.dispatch( api.endpoints.setCurrentScenario.initiate( 1 ) ); const currentScenario = store.getState().scenarios.current; console.log({currentScenario}); expect(currentScenario?.name).not.toBeNull(); }) })
额外注意点
你定义的scenario、milestones、groups三个endpoint的query函数中,参数是{theid}但使用了未定义的scenarioId,这是笔误,需要修正为:
scenario: builder.query({ query: ({theid}) => `scenarios/${theid}`}), milestones: builder.query({ query: ({theid}) => `scenarios/${theid}/ml`}), groups: builder.query({ query: ({theid}) => `scenarios/${theid}/pg`}),
内容的提问来源于stack exchange,提问作者Santiago
相关产品推荐
相关产品推荐

