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

react-testing-library中Lottie模拟失效及TypeError报错问题求助

Fixing TypeError: Cannot set property 'fillStyle' of null with react-lottie in Jest Tests

I’ve run into this exact issue before—let’s get your tests working properly. The error pops up because react-lottie relies on canvas APIs under the hood, and even with jest-canvas-mock set up, the real component might still try to access canvas elements that don’t exist in a Jest test environment. Here’s how to mock react-lottie effectively:

Option 1: Mock in Individual Test Files

If you only need to mock the library for specific test files, add this snippet at the very top (before your import statements):

jest.mock('react-lottie', () => ({
  __esModule: true,
  default: () => <div data-testid="mock-lottie-component" />,
}));

This replaces the real react-lottie component with a simple <div> that you can even target in your tests (using the data-testid) to verify it’s rendering as expected. No more canvas-related errors!

Option 2: Global Mock for All Tests

If every test that uses react-lottie needs this mock, set up a global mock to avoid repeating code:

  1. Create a __mocks__ folder at your project root (if it doesn’t exist already).
  2. Inside it, make a file named react-lottie.ts with this code:
import React from 'react';

const MockLottie = () => <div data-testid="global-mock-lottie" />;

export default MockLottie;
  1. Update your jest.config.ts to ensure Jest uses this mock consistently (Jest often auto-detects the __mocks__ folder, but this explicit mapping guarantees it):
import type { Config } from '@jest/types';

const config: Config.InitialOptions = {
  verbose: true,
  setupFiles: ['jest-canvas-mock'],
  moduleNameMapper: {
    'react-lottie': '<rootDir>/__mocks__/react-lottie.ts'
  }
};

export default config;

Quick Validation

After setting up the mock, run your tests again. You can even add an assertion to confirm the mock is working:

import { render, screen } from '@testing-library/react';
import YourComponent from './YourComponent';

test('renders mock lottie component', () => {
  render(<YourComponent />);
  expect(screen.getByTestId('mock-lottie-component')).toBeInTheDocument();
});

A quick note: Make sure jest-canvas-mock is loading first in your setupFiles—your current config looks correct for that, but if you still see canvas-related quirks, double-check the order of your setup files.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 20:07:35