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

测试React组件时出现TextDecoder is not defined错误的解决方法

问题

我开发了一个用Firebase实现身份验证与实时数据库的React项目,为组件编写了测试用例验证下拉选择框默认选项为us和technology,但运行测试时,在引入getAuth()、ref()等Firebase方法的配置文件中出现TEXTDECODER IS NOT DEFINED错误。

错误信息

src/components/News.test.js
  ● Test suite failed to run

    ReferenceError: TextDecoder is not defined

      1 | import { initializeApp } from "firebase/app";
      2 | import { getDatabase, ref, set, } from "firebase/database";
    > 3 | import { getAuth } from "firebase/auth";
        | 

测试代码

import React from 'react';
import { render,} from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import News from './News';

test('renders with default option "Technology"', async () => {
  const { getByLabelText } = render(<News />);

  const countrySelect = getByLabelText('Country:');
  const categorySelect = getByLabelText('Category:');


  expect(countrySelect).toHaveValue('us'); // Assuming 'us' is the default country
  expect(categorySelect).toHaveValue('technology'); // Assuming 'technology' is the default category
});

解决方法

这个错误是因为Jest运行的Node环境中缺少浏览器提供的TextDecoder全局对象,而Firebase部分模块依赖该对象,可通过以下方式解决:

  • 在测试文件顶部添加全局模拟
    在News.test.js最顶部添加代码,手动模拟TextDecoder:

    global.TextDecoder = require('util').TextDecoder;
    

    若使用Node.js v16+,可简化为:

    global.TextDecoder = TextDecoder;
    
  • 在Jest全局配置中注入
    项目根目录新建或修改jest.config.js,添加setupFiles配置指定全局初始化文件:

    module.exports = {
      setupFiles: ['./src/test-setup.js'],
      // 其他Jest配置项
    };
    

    然后在src/test-setup.js中写入:

    global.TextDecoder = require('util').TextDecoder;
    
  • 模拟Firebase模块避免真实依赖加载
    若仅测试组件UI,无需验证Firebase功能,可使用jest.mock模拟Firebase模块:
    在测试文件顶部添加:

    jest.mock('firebase/app', () => ({
      initializeApp: jest.fn(),
    }));
    jest.mock('firebase/auth', () => ({
      getAuth: jest.fn(),
    }));
    jest.mock('firebase/database', () => ({
      getDatabase: jest.fn(),
      ref: jest.fn(),
      set: jest.fn(),
    }));
    

    测试时会使用模拟的Firebase方法,不会触发真实依赖加载,从而规避TextDecoder问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 23:25:05