假设有一个 Umi 框架下的 Dva model:

export default {
  namespace: 'example',
  state: {
    count: 0,
  },
  reducers: {
    add(state) {
      return { ...state, count: state.count + 1 };
    },
    minus(state) {
      return { ...state, count: state.count - 1 };
    },
  },
};

我们可以编写如下的 Jest 测试用例来模拟 dispatch:

import exampleModel from '@/models/example';

describe('example model', () => {
  it('should add count when dispatch add', () => {
    const { reducers } = exampleModel;
    const state = { count: 0 };
    const newState = reducers.add(state);
    expect(newState.count).toBe(1);
  });

  it('should minus count when dispatch minus', () => {
    const { reducers } = exampleModel;
    const state = { count: 1 };
    const newState = reducers.minus(state);
    expect(newState.count).toBe(0);
  });

  it('should not change state when dispatch unknown action', () => {
    const { reducers } = exampleModel;
    const state = { count: 0 };
    const newState = reducers.unknown(state);
    expect(newState).toBe(state);
  });
});

这些测试用例分别测试了当 dispatch 触发不同的 action 时,model 中的 state 是否会正确更新。其中第三个测试用例测试了当 dispatch 一个未知的 action 时,model 中的 state 是否会保持不变。

Umi 框架 Jest 单元测试用例:模拟 Dispatch 行为

原文地址: https://www.cveoy.top/t/topic/oijI 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录