惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Vercel News
Vercel News
The GitHub Blog
The GitHub Blog
博客园 - 【当耐特】
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Recent Announcements
Recent Announcements
D
Docker
GbyAI
GbyAI
酷 壳 – CoolShell
酷 壳 – CoolShell
WordPress大学
WordPress大学
The Cloudflare Blog
雷峰网
雷峰网
A
About on SuperTechFans
小众软件
小众软件
博客园 - Franky
博客园 - 聂微东
F
Full Disclosure
大猫的无限游戏
大猫的无限游戏
C
Check Point Blog
MongoDB | Blog
MongoDB | Blog
G
Google Developers Blog
Microsoft Azure Blog
Microsoft Azure Blog
U
Unit 42
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
V
V2EX
Engineering at Meta
Engineering at Meta
宝玉的分享
宝玉的分享
aimingoo的专栏
aimingoo的专栏
量子位
P
Proofpoint News Feed
Hugging Face - Blog
Hugging Face - Blog
博客园_首页
罗磊的独立博客
Martin Fowler
Martin Fowler
D
DataBreaches.Net
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
S
Secure Thoughts
Project Zero
Project Zero
L
LangChain Blog
阮一峰的网络日志
阮一峰的网络日志
C
Cybersecurity and Infrastructure Security Agency CISA
T
Tailwind CSS Blog
S
Schneier on Security
Blog — PlanetScale
Blog — PlanetScale
The Hacker News
The Hacker News
Spread Privacy
Spread Privacy
Security Latest
Security Latest
NISL@THU
NISL@THU
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
C
CXSECURITY Database RSS Feed - CXSecurity.com
J
Java Code Geeks

Nx Blog

Sharing Tailwind CSS Styles Across Apps in a Monorepo | Nx Blog How SiriusXM Stays Competitive by Iterating and Getting to Market Fast | Nx Blog Agentic Experience Is the New Developer Experience | Nx Blog Nx Joins the Linux Foundation and the Agentic AI Foundation | Nx Blog A Monorepo Is NOT a Monolith | Nx Blog Why we deleted (most of) our MCP tools | Nx Blog Teach Your AI Agent How to Work in a Monorepo | Nx Blog How Broadcom stays efficient and nimble with monorepos | Nx Blog Why Monorepos are King in the Age of AI | Nx Blog Nx 2026 Roadmap: Expanding Agent Autonomy, Improving Performance, Better Polyglot and More | Nx Blog End to End Autonomous AI Agent Workflows with Nx | Nx Blog Autonomous Agents at Scale | Nx Blog Scaling 700+ Projects: How Nx Became a 'No-Brainer' for Caseware | Nx Blog Configure Tailwind v4 with Angular in an Nx Monorepo | Nx Blog The Missing Multiplier for AI Agent Productivity | Nx Blog A Year of Nx Webinars | Nx Blog Wrapping Up 2025 | Nx Blog Nx 22.3 Release: Angular 21 Support, tsgo Compiler, and Prettier v3 | Nx Blog Nx Cloud Release: Agent Resource Usage | Nx Blog Nx Platform Outperforms DIY Cache by 5x | Nx Blog An Nx Carol: Past, Present, and Future of Your Monorepo | Nx Blog Nx 22.1 Release: Terminal UI on Windows, Storybook 10, Vitest 4, and more! | Nx Blog The Compounding Effect: How Nx Features Multiply Performance Gains | Nx Blog 10 Monorepo Myths Debunked: Separating Fact from Fiction | Nx Blog Nx Cloud Release: Enterprise Task Analytics | Nx Blog Watch and Rebuild Storybook Dependencies with Nx | Nx Blog Book - React for Enterprise: Timeless Architecture for Enterprise Apps | Nx Blog Beyond Remote Cache: Unlock 70% More CI Performance | Nx Blog Nx 22 Release: Expanding the build platform | Nx Blog What's the Point of Generating All This Code If You Can't Merge It? | Nx Blog What's New in Nx Self-Healing CI | Nx Blog Nx Highlights: Smarter AI integration, all-new graph UI, and big new versions of your favorite tools | Nx Blog Making the Case for Smarter Monorepos, and How to Not Get Fooled by Myths | Nx Blog Integrating Biome in 20 Minutes | Nx Blog S1ngularity - What Happened, How We Responded, What We Learned | Nx Blog Stop Babysitting Your PRs: Self-Healing CI Cuts Time to Green by 50% | Nx Blog UKG Unifies Their Codebase and Eliminates CI Overhead to Focus on Customer Value | Nx Blog How Git Worktrees Changed My AI Agent Workflow | Nx Blog Nx Cloud Workspace Graph: See Your Organization's Code Structure Like Never Before | Nx Blog Seamless Java Deployment in Nx Using Docker | Nx Blog Getting Mobile Into Your Monorepo: Android + Nx | Nx Blog Polyglot Projects Made Easy: Integrating Spring Boot into an Nx Workspace | Nx Blog The Journey of the Nx Plugin for Gradle: From Prototype to Production | Nx Blog Combining Predictability and Intelligence With Nx Generators and AI | Nx Blog A New UI For The Humble Terminal | Nx Blog Continuous tasks are a huge DX improvement | Nx Blog New and Improved Module Federation Experience with Nx | Nx Blog A New UI for Nx Migration | Nx Blog Custom Task Runners and Self-Hosted Caching Changes | Nx Blog Enterprise Angular Monorepo Patterns | Nx Blog Using Rspack with Angular | Nx Blog Angular Architecture Guide To Building Maintainable Applications at Scale | Nx Blog Modern Angular Testing with Nx | Nx Blog Nx Update: 20.5 | Nx Blog Are Monorepos the Answer to Better AI-Assisted Development? | Nx Blog Making Cursor Smarter with an MCP Server For Nx Monorepos | Nx Blog React Development for 2025 | Nx Blog Using Apollo GraphQL in an Nx Workspace | Nx Blog Angular State Management for 2025 | Nx Blog Tailoring Nx for Your Organization | Nx Blog Nx Cloud Pipelines Come To Nx Console | Nx Blog Define the relationship with monorepos | Nx Blog See your affected project graph in Nx Cloud | Nx Blog Handling CORS In Your Workspace | Nx Blog Improve your architecture and CI pipeline times with Nx projects | Nx Blog Announcing Nx 20 | Nx Blog Introducing Nx Powerpack | Nx Blog Nx 19.5 is here! Stackblitz, Bun, Incremental Builds for Vite, Gradle Test Atomizer | Nx Blog Introducing Explain with AI | Nx Blog Nx Enterprise Podcast Episode 2: Tine Kondo | Nx Blog Monorepos and CI can be a Mess - Here's How Nx and Nx Cloud Fixed It | Nx Blog Nx Enterprise Podcast Episode 1: Hicham El Hammouchi | Nx Blog Nx 19.0 Release!! | Nx Blog Manage Your Gradle Project using Nx | Nx Blog Making the Argument for Monorepos | Nx Blog Reliable CI. A new execution model fixing both flakiness and slowness | Nx Blog Monorepos - Why Speed Matters | Nx Blog Nx Agents Walkthrough: Effortlessly Fast CI Built for Monorepos | Nx Blog Launch Nx Week Recap | Nx Blog Versioning and Releasing Packages in a Monorepo | Nx Blog Fast, Effortless CI | Nx Blog Introducing @nx/nuxt Enhanced Nuxt.js Support in Nx | Nx Blog What if Nx Plugins Were More Like VSCode Extensions | Nx Blog Monorepos: the Benefits, Challenges, and Importance of Tooling Support | Nx Blog Nx — Highlights of 2023 | Nx Blog Nx 17.2 Update | Nx Blog Nx Docs AI Assistant | Nx Blog State Management Nx React Native/Expo Apps with TanStack Query and Redux | Nx Blog Nx 17 has Landed | Nx Blog Nx Conf 2023 — Recap | Nx Blog Nx Raises $16M Series A | Nx Blog Introducing Playwright Support for Nx | Nx Blog Nx 16.8 Release!!! | Nx Blog Step-by-Step Guide to Creating an Expo Monorepo with Nx | Nx Blog Qwikify your Development with Nx | Nx Blog Create Your Own create-react-app CLI | Nx Blog Storybook Interaction Tests in Nx | Nx Blog Evergreen Tooling — More than Just CodeMods | Nx Blog Nx 16.5 Release!!! | Nx Blog A Practical Guide on Effective AI Use - AI as Your Peer Programmer | Nx Blog
Unit Testing Expo Apps With Jest | Nx Blog
Emily Xiong · 2023-11-23 · via Nx Blog

In my latest blog, I successfully navigated through the steps of setting up an Expo Monorepo with Nx. The next challenge? Testing! This blog dives into:

  • Crafting effective unit tests for Expo components utilizing Jest
  • Addressing common issues encountered during unit testing

Repo:

https://github.com/xiongemi/nx-expo-monorepo

Stacks

Here's my setup

Writing and Running Unit Tests

When you use Nx, it not only configures and sets up Jest, but also creates a default unit test for every expo component that is being generated. Here's what that looks like:

import { render } from '@testing-library/react-native';
import React from 'react';

import Loading from './loading';

describe('Loading', () => {
  it('should render successfully', () => {
    const { root } = render(<Loading />);
    expect(root).toBeTruthy();
  });
});

To run all unit tests for a given project, use:

npx nx test <project-name>

Here's the output of running this for my example app:

terminal output

When it comes to writing tests, the React Native Testing Library is a game-changer for writing cleaner unit tests in React Native applications. Its intuitive query API simplifies the process of selecting elements within your components, making it straightforward to write more maintainable and readable tests. You mark elements with a testID

<Headline testID="title">{film.title}</Headline>

Then in the test file, you can use the function getByTestId to query testID:

const { getByTestId } = render(<your component>);
expect(getByTestId('title')).toHaveTextContent(...);

You can find more options for querying elements on the official React Native Testing Library docs: https://callstack.github.io/react-native-testing-library/docs/api-queries.

Troubleshooting Common Issues When Writing Tests

However, unit tests do not always pass. Here are some common errors I ran into and how to resolve them.

Error: AsyncStorage is null.

I am using the library @react-native-async-storage/async-storage, and I got the below error when running unit testing:

 [@RNC/AsyncStorage]: NativeModule: AsyncStorage is null.

    To fix this issue try these steps:

      • Rebuild and restart the app.

      • Run the packager with `--reset-cache` flag.

      • If you are using CocoaPods on iOS, run `pod install` in the `ios` directory and then rebuild and re-run the app.

      • If this happens while testing with Jest, check out docs how to integrate AsyncStorage with it: https://react-native-async-storage.github.io/async-storage/docs/advanced/jest

    If none of these fix the issue, please open an issue on the Github repository: https://github.com/react-native-async-storage/async-storage/issues

       5 | import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
       6 | import { Platform } from 'react-native';
    >  7 | import AsyncStorage from '@react-native-async-storage/async-storage';

The issue is that @react-native-async-storage/async-storage library can only be used in NativeModule. Since unit testing with Jest only tests JS/TS file logic, I need to mock this library.

In the app's test-setup.ts file, add the below lines:

jest.mock('@react-native-async-storage/async-storage', () =>
  require('@react-native-async-storage/async-storage/jest/async-storage-mock')
);

Error: Could not find "store"

I am using Redux for state management, and I got this error for my stateful components:

Could not find "store" in the context of "Connect(Bookmarks)". Either wrap the root component in a <Provider>, or pass a custom React context provider to <Provider> and the corresponding React context consumer to Connect(Bookmarks) in connect options.

To fix this, the simple way is to mock a redux store. I need to install redux-mock-store and its typing:

npm
npm install redux-mock-store @types/redux-mock-store --save-dev
yarn
yarn add redux-mock-store @types/redux-mock-store --dev

Then I can create a mock store using this library like the below code:

import configureStore, { MockStoreEnhanced } from 'redux-mock-store';

const mockStore = configureStore<any>([]);

let store: MockStoreEnhanced<any>;

beforeEach(() => {
  store = mockStore({});
  store.dispatch = jest.fn();
});

For example, one of my stateful components' unit test will become:

import React from 'react';
import { render } from '@testing-library/react-native';
import { Provider } from 'react-redux';
import configureStore, { MockStoreEnhanced } from 'redux-mock-store';
import { RootState, initialRootState } from '@nx-expo-monorepo/states/cat';

import Bookmarks from './bookmarks';

describe('Bookmarks', () => {
  const mockStore = configureStore<RootState>([]);

  let store: MockStoreEnhanced<RootState>;

  beforeEach(() => {
    store = mockStore(initialRootState);
    store.dispatch = jest.fn();
  });

  it('should render successfully', () => {
    const { container } = render(
      <Provider store={store}>
        <Bookmarks />
      </Provider>
    );
    expect(container).toBeTruthy();
  });
});

The above code will apply the initial redux state to my components.

Error: No QueryClient set

Because I use TanStack Query , when I run unit tests, I have this error:

No QueryClient set, use QueryClientProvider to set one

This error occurred because I used useQuery from @tanstack/react-query in my component; however, in this unit test, the context of this hook is not provided.

To solve this, I can just mock the useQuery function:

import * as ReactQuery from '@tanstack/react-query';

jest.spyOn(ReactQuery, 'useQuery').mockImplementation(
  jest.fn().mockReturnValue({
    data: 'random cat fact',
    isLoading: false,
    isSuccess: true,
    refetch: jest.fn(),
    isFetching: false,
    isError: false,
  })
);

Error: Couldn't find a navigation object

If you use @react-navigation library for navigation, and inside your component, there are hooks from this library like useNavigation and useRoute, you are likely to get this error:

Couldn't find a navigation object. Is your component inside NavigationContainer?

The fix this, I need to mock the @react-nativgation/native library. In the app's test-setup.ts file, I need to add:

jest.mock('@react-navigation/native', () => {
  return {
    useNavigation: () => ({
      navigate: jest.fn(),
      dispatch: jest.fn(),
      setOptions: jest.fn(),
    }),
    useRoute: () => ({
      params: {
        id: '123',
      },
    }),
  };
});

SyntaxError: Unexpected token 'export'

I got this error when using a library with ECMAScript Module (ESM), such as udid:

 /Users/emilyxiong/Code/nx-expo-monorepo/node_modules/uuid/dist/esm-browser/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { default as v1 } from './v1.js';
                                                                                      ^^^^^^

    SyntaxError: Unexpected token 'export'

       5 | import { connect } from 'react-redux';
       6 | import 'react-native-get-random-values';
    >  7 | import { v4 as uuidv4 } from 'uuid';

Jest does not work with ESM out of the box. The simple solution is to map this library to the CommonJS version of this library.

In the app's jest.config.ts, there should be an option called moduleNameMapper. The library I used is called uuid, so I need to add the map uuid: require.resolve('uuid') under moduleNameMapper. So when the code encounters imports from uuid library, it will resolve the CommonJS version of it:

module.exports = {
  moduleNameMapper: {
    uuid: require.resolve('uuid'),
  },
};

Alternatively, I can also mock this library in the test files:

import { v4 as uuidv4 } from 'uuid';

jest.mock('uuid', () => {
  return {
    v4: jest.fn(() => 1),
  };
});

Error: Jest encountered an unexpected token

I got this error when I was importing from a library such as react-native-vector-icons:

 console.error
      Jest encountered an unexpected token

      Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

      Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

      By default "node_modules" folder is ignored by transformers.

      Here's what you can do:
       • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
       • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
       • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
       • If I need a custom transformation specify a "transform" option in my config.
       • If I simply want to mock my non-JS modules (e.g. binary assets) I can stub them out with the "moduleNameMapper" config option.

      You'll find more details and examples of these config options in the docs:
      https://jestjs.io/docs/configuration
      For information about custom transformations, see:
      https://jestjs.io/docs/code-transformation

To fix this, add this library name to transformIgnorePatterns in the app's jest.config.ts.

What is transformIgnorePatterns? The transformIgnorePatterns allows developers to specify which files shall be transformed by Babel. transformIgnorePatterns is an array of regexp pattern strings that should be matched against all source file paths before the transformation. If the file path matches any patterns, it will not be transformed by Babel.

By default, Jest will ignore all the files under node_modules and only transform the files under the project's src.

However, some libraries such as react-native-paper or react-native-svg, the library files are in .ts or .tsx. These files are not compiled to js. So I need to add these libraries' names to transformIgnorePatterns, so these libraries will be transformed by Babel along with my project. source file. The default generated jest.config.js already has:

transformIgnorePatterns: [
    'node_modules/(?!((jest-)?react-native|@react-native(-community)?)|expo(nent)?|@expo(nent)?/.*|@expo-google-fonts/.*|react-navigation|@react-navigation/.*|@unimodules/.*|unimodules|sentry-expo|native-base|react-native-svg)',
]

If I have an error related to a library with an unexpected token, I need to check whether they are compiled or not.

  • If this library source files are already transformed to .js, then its name should match regex, so it would be ignored, so it will NOT be transformed.
  • If this library source files are NOT transformed to .js (e.g. still in .ts or .tsx), then its name should NOT match regex, so it will be transformed.

Summary

Here are some common errors that I will probably run into while doing unit testing. The solution to most problems is to find a way to mock a library that is not relevant to my component logic.

With Nx, I do not need to explicitly install any testing library, so I can dive right in and focus on writing the tests rather than spending time on setup.

Learn more