我面临一个奇怪的问题。
我的全局状态中有一个对象,需要使用 3 个不同的 API 端点调用来填充。
所以我选择使用
onQueryStarted
方法设置一个特定查询。这是
endpoints
服务的 api.ts
:
{
scenario: builder.query({ query: ({theid}) => `scenarios/${scenarioId}`}),
milestones: builder.query({ query: ({theid}) => `scenarios/${scenarioId}/ml`}),
groups: builder.query({ query: ({theid}) => `scenarios/${scenarioId}/pg`}),
setCurrentScenario: builder.query({
query: id => `scenarios/${id}`,
async onQueryStarted (id, { dispatch, queryFulfilled, getState }) {
try {
let ml = await api.endpoints.milestones.initiate({theid: id})(dispatch, getState, "api")
let pg = await api.endpoints.groups.initiate({theid: id})(dispatch, getState, "api")
let currentScen = await queryFulfilled
dispatch( scenarioActions.addCurrentScenario( currentScen.data ))
dispatch( scenarioActions.addCurrentScenarioMilestones( ml.data ))
dispatch( scenarioActions.addCurrentScenarioPlayerGroups( pg.data ))
} catch (error) {
console.log('ERRORE IN SETCURRENTSCENARIO: ', error)
}
}
这工作正常,但是当我测试时,我需要添加一些“睡眠”功能,尽管事实上我
dispatch
带有setCurrentScenario
端点:await
我不明白,如果我在那个
describe('A single Scenario should be fetched if user is manager', () => {
it('should populate `current` scenario after asking with its `id`', async () => {
// this populates `state.scenarios.current`
await store.dispatch( api.endpoints.setCurrentScenario.initiate( 1 ) )
const sleep = (time:number) => new Promise((reslv) => setTimeout(reslv, time));
await sleep(1000)
const currentScenario = store.getState().scenarios.current
console.log({currentScenario})
expect(store.getState().scenarios.current?.name).not.toBeNull()
})
})
上使用
await
,为什么我需要睡觉?感谢您给我的任何帮助。
store.dispatch()
的意思是“这样做,我们稍后继续执行我们的代码”。
其他代码(在本例中为您的测试)可以在两者之间运行。 因此,您的测试必须完成,直到所有事情都完成并且所有“稍后”的代码也执行完毕。