首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在redux中对异步调用进行单元测试/存根

在Redux中对异步调用进行单元测试/存根的方法有多种。下面是一种常见的方法:

  1. 使用redux-mock-store库:redux-mock-store是一个用于创建模拟Redux store的库,它可以帮助我们在测试中模拟Redux store的行为。首先,安装redux-mock-store库:
代码语言:txt
复制
npm install --save-dev redux-mock-store
  1. 创建模拟store:在测试文件中,首先导入redux-mock-store和要测试的异步action创建函数。然后,使用redux-mock-store创建一个模拟store,并将其传递给异步action创建函数。
代码语言:txt
复制
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { fetchUser } from './actions';

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

describe('Async actions', () => {
  it('should dispatch the correct actions on successful API call', () => {
    const store = mockStore({}); // 创建一个模拟store

    return store.dispatch(fetchUser()).then(() => {
      const actions = store.getActions();
      expect(actions[0]).toEqual({ type: 'FETCH_USER_REQUEST' });
      expect(actions[1]).toEqual({ type: 'FETCH_USER_SUCCESS', payload: { /* 用户数据 */ } });
    });
  });
});

在上面的示例中,我们创建了一个模拟store,并使用store.dispatch调用了fetchUser异步action创建函数。然后,我们使用store.getActions()获取store中的所有action,并对其进行断言。

需要注意的是,上述示例中的fetchUser异步action创建函数应该返回一个Promise,以便在测试中使用.then()进行链式调用。

这种方法可以帮助我们对Redux中的异步调用进行单元测试,并验证在不同情况下是否正确地触发了相应的action。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的视频

领券