Testing React Native With the New Jest - Part II

Authors
Ferran Negre
Software Engineer
@
Callstack

It’s a well known paradigm in the React world for any big app you want to write to extract your business logic (aka manage the state of your app) out of your components. The majority of your components should be a small piece of reusable code that just renders UI based on the app state that is triggered mainly by: User input and API calls. The same paradigm is used in React Native.

I will talk about Redux together with React Native since testing Redux is easy. However feel free to apply the same concepts to another state management you choose. That’s what we will do here:

  • Testing Reducers: Manual comparison vs. Snapshots
  • Mock the built-in React Native fetch
  • Re-mock the redux-mock-store
  • Testing Actions (including async ones): Manual comparison vs. Snapshots

Please refer to Unit testing React Native with the *new* Jest (I)  for setting up Jest with React Native.

Reducers

Testing a reducer might be one of the easiest parts to test from your app: Given the current state and an action, a reducer should return a new state after that action is applied. Let’s see how to test part of this example:

export const initialState = { // Exporting it for test purposes
error: null,
isLoading: false,
repos: null,
selected: null,
};
export default function repos(state = initialState, action) {
switch (action.type) {
case LOAD_REPOS.failure:
return {...state, error: action.error, isLoading: false};
case LOAD_REPOS.request:
return {...state, isLoading: true};
case LOAD_REPOS.success:
return {...state, isLoading: false, repos: action.data};
case SELECT_REPO:
const selected = state.selected !== action.id ? action.id : null;
return {...state, selected};
default:
return state;
}
}

We will focus on testing that LOAD_REPOS.success action. Let’s create version 1 of our test:

expect(repos(initialState, receiveRepos.success(data))).toEqual({
error: null,
isLoading: false,
repos: data,
selected: null,
});

Copy & paste again :(

Quite short, right? I just went and copied and pasted the initialStatefrom my reducer and added the part that changes (repos). When you work in larger projects and your state starts to grow (0r you do some refactoring), you will find this process to be so repetitive that you will want to do something better, so, version 2:

expect(repos(initialState, receiveRepos.success(data))).toEqual({
...initialState,
isLoading: false,
repos: data
});

Reimplementing the reducer :(

This is better, right? I can add or delete anything to the state (except the isLoading & repos part) and I won’t break the test. I just need to go back here if that action.success does actually affect another part of the state in the future. But, don’t you feel that test it is actually very similar to:

case LOAD_REPOS.success:
return {...state, isLoading: false, repos: action.data};

Again, what we are doing in the test is basically reimplementing the reducer. Anytime I change the logic in my reducer, I need to come back here and do the same. It get’s so repetitive… Can we do better? Let’s snapshot that output. Hello version 3:

expect(repos(initialState, receiveRepos.success(data))).toMatchSnapshot();

Given the state and an action, generate the output for me

I know, it’s just one line and I did not have to repeat myself at all (DRY?). Do you like it? I do! Let’s see what the snapshot looks like:

exports[`test handles LOAD_REPOS_SUCCESS action 1`] = `
Object {
"error": null,
"isLoading": false,
"repos": Array [
Object {
"description": "Useful description goes here.",
"id": 1,
"name": "Test 1",
"stargazers_count": 50000
},
Object {
"description": "Useful description goes here.",
"id": 2,
"name": "Test 2",
"stargazers_count": 10000
},
Object {
"description": "Useful description goes here.",
"id": 3,
"name": "Test 3",
"stargazers_count": 499
}
],
"selected": null
}
`;

Wow! I can actually see how my state will exactly look like after applying the action. So as you can see, we are forcing Jest to do the hard work while we are just watching. In this case, if you add or remove any part of your state, this test will break: Which is what you should expect, since the outputted state would be different. But as I explained in the first part of these series, the only thing we need to do here is:

  • Review the Jest error output
  • If it’s expected, run the test again using -u to re-generate the snapshot:
npm test -— -u YourTestName
  • If it’s not expected, go and fix it (obviously)

This is a great example of how fast and easy is to write your tests first, aka TDD (Test-driven development):

  1. Write your test first
  2. Start writing your reducer with the Jest — watch mode enabled
  3. Once the outputted snapshot is the one you are expecting, just tell Jest to save it
  4. Done!

Actions

A simple action creator is just a function that returns an object:

export const selectRepo = (id) => {
return {
type: SELECT_REPO,
id
}
};

Simple action creator

Which can be tested like:

it('creates a SELECT_REPO action', () => {
// You do it
expect(selectRepo(1000)).toEqual(
{
type: SELECT_REPO,
id: 1000
}
);
// Jest does it
expect(selectRepo(1000)).toMatchSnapshot();
});

For the second part, let’s check out the generated snapshot:

exports[`test creates a SELECT_REPO action 1`] = `
Object {
"id": 1000,
"type": "SELECT_REPO"
}
`;

Yea, the exact same thing as the reducer: I (and my team) can read the output instead of re-creating the action again (which includes the need to maintain that code in both places).

By the way, if you are already bored of reading, you can watch the same concept in a nice and short explanation thanks to Kent C. Dodds. If you are not, let’s continue. Since testing such simple actions is so meh, let’s go and test an async action that uses the built-in fetch of React Native and dispatches more than one action at once.

Async actions

This is the async action we will test:

export const fetchData = (endpoint, fetchAction) => async (dispatch) => {
try {
dispatch(fetchAction.request());
const response = await fetch(endpoint);
const responseJson = await response.json();
dispatch(fetchAction.success(responseJson.items));
} catch (error) {
dispatch(fetchAction.failure(error));
}
};

We need some mocking help here to be able to have a nice way to test that so… Let’s mock!

Mocking the built-in fetch of React Native

Similar way that you can use whatwg-fetch in your web apps which will include a fetch polyfill into window.fetch, React Native uses the same idea and includes fetch into the global object as global.fetch.

We don’t want to make real api calls into our unit tests but we would like to mock the responses to write better assertions. There are some mock libraries out there but I just wrote a smaller version that fits my purposes:

// Mocking the global.fetch included in React Native
global.fetch = jest.fn();
// Helper to mock a success response (only once)
fetch.mockResponseSuccess = (body) => {
fetch.mockImplementationOnce (
() => Promise.resolve({json: () => Promise.resolve(JSON.parse(body))})
);
};
// Helper to mock a failure response (only once)
fetch.mockResponseFailure = (error) => {
fetch.mockImplementationOnce(
() => Promise.reject(error)
);
};

Mocking fetch

Then, we can tell Jest to load that config using the package.json field setupFiles:

"jest": {<br> ...<br><strong> "setupFiles": [<br> "./config/jest/globalFetch.js"<br> ]</strong><br>}
view raw "jest": hosted with ❤ by GitHub

You will see when we are testing our async action how I used this mock. For now, let’s continue mocking.

Mocking a Redux store

I am sure that a lot of Redux users are familiar with redux-mock-store. It’s a simple helper that provides a mocked version of the Redux store and makes it very easy to test what actions have been called. Once you have your mocked store, you can use store.dispatch and get the list of actions that has been dispatched using store.getActions.

But you know what? I feel so lazy that I don’t want to do the same in all my tests where I need a store and a thunk, so I am going to re-mock the redux-mock-store module. See, in Jest you can create a __mocks__folder in the same level as your node_modules to mock any npm module. So I can actually create a redux-mock-store.js file (name of the module) in the __mocks__ folder:

// __mocks__/redux-mock-store.js
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
const middlewares = [ thunk ];
const mockStore = configureMockStore(middlewares);
export default mockStore;

And use it in my tests like:

// Usage
import mockStore from 'redux-mock-store';

Lazy, eh?

Async test

I feel that we are ready to test our async action now, don’t you? Basically what we want to test here is:

  1. A successful request should trigger request & success actions
  2. A failure request should trigger request & failure actions

First case:

it('should handle TEST_API_SUCCESS action', async () => {
const response = '{"items": [{"id": 1}]}';
fetch.mockResponseSuccess(response);
await store.dispatch(fetchData('/test', receiveTestData));
expect(store.getActions()).toMatchSnapshot();
});

Rather short, right?

And what output will be generated?

exports[`test should handle TEST_API_SUCCESS action 1`] = `
Array [
Object {
"type": "TEST_API_REQUEST"
},
Object {
"data": Array [
Object {
"id": 1
}
],
"type": "TEST_API_SUCCESS"
}
]
`;

Just as expected and in this case, I think this one is very useful and easy to read: Quick read by reading “type” and longer read by checking that actually the “data” matches what we told fetch to return.

The second case is very similar:

it('should handle TEST_API_FAILURE action', async () => {
const mockError = new Error('Look ma! I am an error.');
fetch.mockResponseFailure(mockError);
await store.dispatch(fetchData('/test', receiveTestData));
expect(store.getActions()).toMatchSnapshot();
});

And its output:

exports[`test should handle TEST_API_FAILURE action 1`] = `
Array [
Object {
"type": "TEST_API_REQUEST"
},
Object {
"error": [Error: Look ma! I am an error.],
"type": "TEST_API_FAILURE"
}
]
`;

As you can see, when you have the mocks in place, writing this kind of tests become very straightforward, and most likely, you won’t need to mock anything since you can find them out there or write your own and reuse them for other projects.

Wrap up

This is it, with this part and the first one, we pretty much covered (I hope) unit testing of your React Native components + your state management logic. We also re-discovered Jest and its new superpower: Snapshots. On contrary, I am sure the way to test React Native apps will continue to improve as much as Jest keeps growing. So this article might get out of date quite soon!

Let me finish with some personal thoughts:

Why would I use Jest?

  • You can easily test your React & React Native components
  • Snapshots are a plus, but they are totally optional
  • You can easily test Redux or other state management libraries with Jest: Shared logic between web and mobile could share tests too!
  • The same community have created React Native & Jest. What does that mean? They will be the ones who care the most about making React Native and Jest to play nicely together in the future

To sum up: If you test your web & mobile app with Jest, you can use the same core principle of React Native:

Learn once, write anywhere — React Native

Of course, that is only my opinion. I just hope you enjoyed this short journey about testing a React Native app with the new Jest and remember… Happy testing!

You can also check our services offered by our React Native development company.

Insights

Learn more about Testing

How AI Agents Can Cut Manual QA by 30% — cover

Oct 30Article

How AI Agents Can Cut Manual QA by 30%

Explore an agentic QA workflow targeting 30% less manual effort across mobile, web, and TV, with test selection, failure triage, and validation.

Give QA Agents the Controls They Need With Appduct — cover

Oct 20Article

Give QA Agents the Controls They Need With Appduct

Use Appduct to give AI QA agents access to app functions for setting test conditions, triggering events, and checking results with UI automation.

cover

Oct 13Article

Agentic Mobile Testing With e2e and agent-device

See how e2e uses agent-device for AI-driven iOS and Android tests, combines exact assertions with agent actions, and replays cached steps without model calls.

Who Tests AI-Written Code? Inside TesterArmy With Szymon Rybczak — cover

Oct 12Podcast

Who Tests AI-Written Code? Inside TesterArmy With Szymon Rybczak

Szymon Rybczak explains how TesterArmy tests web and mobile apps with AI agents, creates test plans for pull requests, and fits into QA workflows.

cover

Aug 4Article

Automating Mobile QA With Cloud Agents

Code review and green CI checks do not prove a mobile app still works. Learn how cloud agents, agent-device, and runtime evidence can verify app behavior before merge.

cover

Jul 21Webinar

Behavior Review for AI-Native Delivery

AI can increase code output faster than teams can verify the real app. See why behavior review matters before merge.

cover

Jul 6Article

Introducing Sniffler: Run only the E2E tests your changes can affect

Sniffler maps changed files to affected E2E tests, so teams can avoid running the full suite on every pull request.

cover

Jun 17Talk

Automating Mobile QA with Cloud Agents

Michał Pierzchała will present Automating Mobile QA with Cloud Agents at Ship London on 17 June 2026.

cover

May 13Podcast

How AI Is Changing React Native Development and Testing

Zack Ebenfeld joins React Universe On Air to talk about how AI is changing React Native workflows, testing, QA, and day-to-day engineering work.

cover

Apr 14Article

Agent React DevTools: Give AI Agents Access to React Internals

Agent React DevTools gives AI agents access to the React component tree, state, and performance data, enabling deeper debugging and more reliable QA for React and React Native apps.

cover

Mar 19Live Stream

Agent Device, AI workflows, and mobile testing in practice

A discussion on Agent Device, AI-driven workflows, and testing mobile apps using simulators and accessibility data.

cover

Aug 23Podcast

Introducing E2E Tests to React Native Core

This episode of the React Native Show dives into the recent introduction of End-to-End (E2E) testing in RNTester. Join us as we unpack the thought process, technical considerations, and practical implementation of this new approach to testing in React Native.

cover

Mar 19Tutorial

The Hard Way vs. The React Native AI SDK Way: Stop Writing Custom Modules for Every Model

Learn how React Native AI uses a unified provider model to switch between cloud and on-device LLMs without rewriting application logic, enabling reliable AI experiences online and offline.

cover

Mar 12Tutorial

Build Smarter Apps: Tool Calling & AI Orchestration Explained

Learn how on-device models in React Native can call tools, interact with external APIs, and return structured outputs you can use directly in application logic.

cover

Mar 5Tutorial

MLC LLM + React Native: On-Device AI Without the Pain

Learn how to run third-party on-device LLMs in React Native using MLC LLM. Choose your models, run them efficiently across platforms, and keep a unified JavaScript API with React Native AI.

cover

Feb 24Tutorial

Intelligent Fallbacks with Apple Intelligence in React Native

Learn how to use Apple’s built-in Foundation Models in React Native apps, reduce memory usage, and enable fast, fully on-device AI with React Native AI Apple.

cover

Feb 10Tutorial

What Is the React Native AI SDK? A Complete Intro & Quickstart

Learn why on-device AI matters for React Native apps, how local LLMs behave offline, and what problems React Native AI is designed to solve from day one.

cover

Jan 29Tutorial

Implementing an Android TurboModule with Kotlin

Learn how to implement a React Native TurboModule on Android, from the TypeScript spec and Codegen to the Kotlin implementation and package registration.

cover

Jan 19Tutorial

Working with Different Threads in Swift TurboModules

Learn how JavaScript, native module, background, and main threads interact in React Native TurboModules, and how to use GCD queues to run async work safely in Swift.

cover

Jan 9Tutorial

How to Add Type-Safe Constants to Swift TurboModules

Learn how to expose typed, immutable constants from a Swift TurboModule using Codegen, and get full end-to-end type safety between native and JavaScript.

cover

Dec 30Tutorial

Adding Event Emitters to Your TurboModule in Swift

Learn how to emit native events from a Swift TurboModule and subscribe to them in JavaScript, including proper memory management and Codegen integration.

cover

Dec 22Tutorial

Writing Your First TurboModule in Swift

Learn how to build a fully working TurboModule in Swift, integrate it with Codegen, and bridge it through Objective‑C inside an Expo app.