store.getActions()在部分测试中无法返回action的问题求助
问题:测试Redux Action派发时
store.getActions()在部分用例中无返回值 我在测试Redux Action是否正确派发时,发现store.getActions()方法在一个测试用例中能正常返回结果,但在另一个用例里完全拿不到任何数据。不过失败的那个用例里,用getByText这类基础测试方法配合mock-store数据测试组件是正常的。
失败的测试用例代码
test('setButtons action dispatched on button click', () => { const store = mockStore(initialState); const { getByText } = render( <Provider store={store}> <MemoryRouter> <Comments /> </MemoryRouter> </Provider> ); const button = getByText('Posts') fireEvent.click(button); const actions = store.getActions(); const expectedAction = setButtons('Show Comments'); console.log('Expected Action Comment:', expectedAction); console.log('Actions Comment:', actions); expect(actions).toContainEqual(expectedAction); });
对应日志输出
console.log Expected Action Comment: { type: 'comments/setButtons', payload: 'Show Comments' } at Object.<anonymous> (src/features/Comments/__test__/Comments.test.js:90:11) console.log Actions Comment: []
正常工作的测试用例代码
test('setButtons action dispatched on button click', () => { const store = mockStore(initialState); const { getAllByText } = render( <Provider store={store}> <MemoryRouter> <Posts /> </MemoryRouter> </Provider> ); const button = getAllByText('Comments') fireEvent.click(button[0]); const actions = store.getActions(); const expectedAction = setButtons('Hide Comments'); console.log('Expected Action Posts:', expectedAction); console.log('Actions Posts:', actions); expect(actions).toContainEqual(expectedAction); });
对应日志输出
console.log Expected Action Posts: { type: 'comments/setButtons', payload: 'Hide Comments' } at Object.<anonymous> (src/features/Posts/__test__/Posts.test.js:108:11) console.log Actions Posts: [ { type: 'comments/setSelectedComments', payload: undefined }, { type: 'comments/setSelectedCommentsTitle', payload: 'Post 1' }, { type: 'comments/setButtons', payload: 'Hide Comments' } ]
内容的提问来源于stack exchange,提问作者Richie
相关产品推荐
相关产品推荐

