首页 > 解决方案 > Enzyme:如何测试容器组件的 props 变化?

问题描述

为了渲染连接到 redux 存储的容器组件,我使用这个函数来渲染组件

function render(Component, props, storeData) {
  const mockStore = configureStore([thunkMiddleware]);
  const store = mockStore(storeData);

  return mount(
    <Provider store={store}>
      <Component {...props} />
    </Provider>
  );
}

现在,我需要测试渲染的组件的 props 更改,但它看起来ReactWrapper.setProps只适用于 Root 组件。
MyComponent是一个容器组件,它使用connect.

describe('MyComponent', () => {
  it('should work at props change', () => {
    const wrapper = render(MyComponent, { value: 1 }, initialStoreValue);

    wrapper.find(MyComponent).setProps({ value: 2});
    
    // then expect something.
  });
});

标签: reactjsunit-testingreduxjestjsenzyme

解决方案


有几点需要考虑:

  1. redux-mock-store允许将函数作为状态源传递 -redux-mock-store每次都会调用该函数
  2. 触发重新渲染组件,useSelector或者connect()我们可以dispatch()使用任何动作类型。从字面上看。
  3. 我们需要将更新存储包装到act(),否则它可能无法正常工作,并且肯定会抱怨console.error.

所以记住这一点,我们可以增强render

function render(Component, props, initialStoreData) {
  let currentStoreData = initialStoreData;
  const mockStore = configureStore([thunkMiddleware]);
  const store = mockStore(() => currentStoreData);

  const wrapper = mount(
    <Provider store={store}>
      <Component {...props} />
    </Provider>
  );
  const updateStore = (newStoreData) => {
    currentStoreData = newStoreData;
    act(() => {
      store.dispatch({ type: '' }); // just to trigger re-rendering components
    });
  }
  return { wrapper, updateStore };
}

然后在测试中:

describe('MyComponent', () => {
  it('does something when store changes somehow', () => {
    const { wrapper, updateStore } = render(MyComponent, { value: 1 }, initialStoreValue);
    
    updateStore({ someReduxValue: 2});

    // then expect something.
  });
});

推荐阅读