📜  react native test redux - Javascript(1)

📅  最后修改于: 2023-12-03 15:34:38.670000             🧑  作者: Mango

React Native Test Redux

React Native Test Redux is a library that helps developers test React Native applications that use Redux as the state management tool.

Installation

To install React Native Test Redux, simply run the following command:

npm install --save-dev @testing-library/react-native react-test-renderer redux-mock-store

This command installs the required dependencies for testing React Native applications with Redux.

Getting Started

To get started with testing a React Native app that uses Redux, create a file called App.test.js in the same directory as your App.js file.

import 'react-native';
import React from 'react';
import App from './App';

// Import the dependencies needed for testing Redux
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import rootReducer from './reducers';

// Import the dependancies for testing the UI
import renderer from 'react-test-renderer';

// Create a mock store
const mockStore = createStore(rootReducer);
 
it('renders correctly', () => {
  const tree = renderer.create(
    <Provider store={mockStore}>
      <App />
    </Provider>
  ).toJSON();
  expect(tree).toMatchSnapshot();
});

In this example, we assume that the App.js file has already been created.

Explanation

The test file is importing several dependencies, including Provider and createStore from react-redux.

The Provider is a higher-order component that allows the entire app to access the Redux store.

<Provider store={mockStore}>

The createStore function is used to create a mock version of the store that the application will use.

const mockStore = createStore(rootReducer);

Once the dependencies have been imported, we can create a test case using the renderer property from react-test-renderer.

renderer.create(
  <Provider store={mockStore}>
    <App />
  </Provider>
).toJSON();

Finally, we're using Jest's toMatchSnapshot function to compare the output of the test to a snapshot of the actual output.

expect(tree).toMatchSnapshot();

This ensures that any changes to the output of the app are intentional and tests will fail if the output changes in an unintended way.

Summary

React Native Test Redux is a powerful library that helps developers test their React Native applications that use Redux for state management.

In this guide, we walked through the steps to install and use the library to ensure that our React Native + Redux applications are robust, reliable, and bug-free.