7

我正在尝试使用 Jest 和 Typescript 测试我的 LoginScreen。我使用 redux 和 redux-persist 进行存储,并将存储设置为使用 AsyncStorage 作为配置的一部分。我怀疑 redux-persist 在它使用的内置超时功能用完并尝试将存储设置为默认存储后尝试补水?我收到以下错误:

console.error
redux-persist: rehydrate for "root" called after timeout. undefined
undefined
at _rehydrate (node_modules/redux-persist/lib/persistReducer.js:70:71)
at node_modules/redux-persist/lib/persistReducer.js:102:11
at tryCallOne (node_modules/promise/setimmediate/core.js:37:12)
at Immediate._onImmediate (node_modules/promise/setimmediate/core.js:123:15)

目前我的测试如下所示:

describe('Testing LoginScreen', () => {
  it('should render correctly', async () => {
    const { toJSON } = render(<MockedNavigator component={LoginScreen} />);
    await act(async () => await flushMicrotasksQueue());
    expect(toJSON()).toMatchSnapshot();
  });
});

我的 MockNavigator 看起来像这样:

type MockedNavigatorProps = {
  component: React.ComponentType<any>;
  params?: {};
};

const Stack = createStackNavigator();
const MockedNavigator = (props: MockedNavigatorProps) => {
  return (
    <MockedStorage>
      <NavigationContainer>
        <Stack.Navigator>
          <Stack.Screen
            name='MockedScreen'
            component={props.component}
            initialParams={props.params}
          />
        </Stack.Navigator>
      </NavigationContainer>
    </MockedStorage>
  );
};

export default MockedNavigator;

这是我创建存储的方式:

import 'react-native-gesture-handler';
import * as React from 'react';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import { store, persistor } from '../src/AppState/store';

type MockedStorageProps = {
  children: any;
};

const MockedStorage = (props: MockedStorageProps) => {
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        {props.children}
      </PersistGate>
    </Provider>
  );
};

export default MockedStorage;
4

1 回答 1

6

redux-persist我使用来自repo上的问题的建议解决了同样的错误: https ://github.com/rt2zz/redux-persist/issues/1243#issuecomment-692609748 。

(它还具有避免在测试中记录错误的副作用redux-logger。)

jest.mock('redux-persist', () => {
  const real = jest.requireActual('redux-persist');
  return {
    ...real,
    persistReducer: jest
      .fn()
      .mockImplementation((config, reducers) => reducers),
  };
});

@alexbrazier:

它基本上只是通过直接返回reducer而不将它们包装在redux-persist中来绕过redux-persist。

于 2020-12-16T13:37:46.333 回答