You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jest中无法测试Styled Component问题求助

Fixing TypeError: styled.View is not a function in Jest Snapshot Tests for React Native

Let's tackle this error step by step — it usually stems from Jest not properly resolving the native version of styled-components in your test environment, even after initial config tweaks. Here are actionable fixes to try:

1. Verify Your moduleNameMapper Path

Double-check that the path in your Jest config points to the correct native build of styled-components. Sometimes the file extension or path can be off depending on your package version:

// jest.config.js
module.exports = {
  moduleNameMapper: {
    'styled-components': '<rootDir>/node_modules/styled-components/dist/styled-components.native.esm.js'
  }
};

Note: Switch to .cjs.js if your project uses CommonJS instead of ES modules.

2. Explicitly Import the Native Version in Your Components

Instead of relying on the default import, explicitly import the native build in your component files. This removes ambiguity for Jest:

// Replace this:
import styled from "styled-components";

// With this:
import styled from "styled-components/native";

3. Update transformIgnorePatterns to Process Styled Components

Jest often skips transforming modules in node_modules, but styled-components' native code needs to be transformed. Add it to your ignore exceptions:

// jest.config.js
module.exports = {
  transformIgnorePatterns: [
    'node_modules/(?!(styled-components|@react-native|react-native)/)'
  ]
};

4. Ensure jest-styled-components is Properly Set Up

Make sure you're importing it in your Jest setup file (usually setupFilesAfterEnv):

// jest.setup.js
import 'jest-styled-components/native';

And link this setup file in your Jest config:

// jest.config.js
module.exports = {
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js']
};

Also, confirm that your jest-styled-components version is compatible with your installed styled-components version (check their docs for version matching).

5. Clear Jest Cache

Sometimes stale cache can cause unexpected issues. Run this command to reset it:

npx jest --clearCache

After trying these steps, re-run your snapshot tests — the error should be resolved.

内容的提问来源于stack exchange,提问作者Dan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 10:00:55