假设有一个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是否会保持不变


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

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