react-testing-library中Lottie模拟失效及TypeError报错问题求助
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:
- Create a
__mocks__folder at your project root (if it doesn’t exist already). - Inside it, make a file named
react-lottie.tswith this code:
import React from 'react'; const MockLottie = () => <div data-testid="global-mock-lottie" />; export default MockLottie;
- Update your
jest.config.tsto 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

