在 React Native 中测试时将空的 Redux Store 传递给组件

问题描述

我正在用 react native 编写单元测试,以根据从 redux 存储中获取的数据类型来显示某些内容。对于当前的实现,假设我将标题显示First Time 如果 details 对象的 category 属性的值设置为 'first' 否则我将显示 Already There 如果值设置为'重复'

Component.js

// All the appropriate and required imports have been done. 

const [heading,setheading] = useState('');
const { details,id } = useSelector(state => state.data);

React.useEffect(()=>{
  if(details.category === 'duplicate')
  setheading('Already There')
  else
  setheading('First time')
},[])

return (
  <Text>{heading}</Text>
)

Component.test.js

import { render } from '@testing-library/react-native';
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { Provider } from 'react-redux';

describe('Component',()=>{
it('Should contain Already There text',() => {
    const middlewares = [thunk];
    const mockStore = configureStore(middlewares);
    let getByText = null;
    const store = mockStore({
      ...initialData,data:{
        id:'XYZ',details:{
          category:'',......
        }
      }
    });
    const mockNavigation= {
      addListener: jest.fn(),navigate: jest.fn()
    };
    store.dispatch = jest.fn();
    const tempWrapper = render(
      <Provider store={store}>
        <Component navigation={mockNavigation}/>
      </Provider>
    )
    ({ getByText } = tempWrapper);
    expect(getByText('Already There')).tobedefined();
  });
})

初始 redux 状态的结构是一个具有以下给定结构的对象:

{
  ....,data:{
    id:'',details:{
      category:'',......
    }
  },....,}

... --> 表示与该组件无关的附加数据

通常状态在这个组件获取数据之前就已经更新了,所以为了模拟它,我在模拟它之前将更新的值存储在 redux store 中。 现在我面临的问题是,在测试时,我将 details 的值作为一个空对象而不是我在渲染它以进行测试之前设置的对象。在正常使用中,组件工作正常,商店正在正确更新,但在测试时,我从商店收到空对象的 details 属性。预期值是我在测试前尝试设置的类别设置为重复的值。

在以这种方式使用商店测试组件之前,我可能遗漏了一些需要采取的步骤。任何帮助将不胜感激。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...