React+TypeScript下使用Jest手动模拟:模拟ES6类依赖
PerformancesResultsReader for AppPage Unit Tests (React + TypeScript) Got it, let's break down how to mock the PerformancesResultsReader module for your AppPage component's unit tests. I'll use Jest (the standard testing framework for React projects) here—this approach will let you isolate your component and avoid running the actual read() method (which might have side effects like hitting real data sources).
1. Mock the entire module
Start by mocking the PerformancesResultsReader module at the top of your test file (e.g., AppPage.component.test.tsx). This replaces the real class with a mock version:
// Mock the PerformancesResultsReader module jest.mock('./../../models/PerformancesResultsReader', () => { // Return a mock class that creates instances with a spy on the read method return jest.fn().mockImplementation(() => { return { read: jest.fn() }; }); });
2. Verify the read() method is called
Once the module is mocked, you can render your component and check that the read() method is invoked as expected:
import PerformancesResultsReader from './../../models/PerformancesResultsReader'; import AppPage from './AppPage.component'; import { render } from '@testing-library/react'; describe('AppPage Component', () => { it('triggers read() on PerformancesResultsReader when mounted', () => { // Render the component (this will run the code that creates the reader instance) render(<AppPage />); // Grab the mock instance created by your component const mockReaderInstance = (PerformancesResultsReader as jest.Mock).mock.instances[0]; // Assert that the read method was called expect(mockReaderInstance.read).toHaveBeenCalled(); }); });
3. Customize mock behavior for test cases
If you need the read() method to return specific data (so you can test how your component handles that data), adjust the mock implementation:
jest.mock('./../../models/PerformancesResultsReader', () => { return jest.fn().mockImplementation(() => { return { // Mock read to return a predefined set of performance results read: jest.fn().mockReturnValue([ { id: 'perf-1', score: 95, metric: 'load-time' }, { id: 'perf-2', score: 88, metric: 'render-speed' } ]) }; }); });
You can then write tests to verify that your component renders this data correctly (e.g., checks if the performance scores show up in the DOM).
4. Fix TypeScript type errors
Since we're mocking a class, TypeScript might throw type mismatches when accessing mock properties. To fix this, cast the mocked class to jest.Mock when accessing instances, or define a typed mock:
// Define a type for the mocked reader instance type MockedPerformancesReader = jest.Mocked<InstanceType<typeof PerformancesResultsReader>>; // In your test: const mockReaderInstance = (PerformancesResultsReader as jest.Mock).mock.instances[0] as MockedPerformancesReader;
This gives you proper type checking for the mocked read() method and any other properties on the class.
内容的提问来源于stack exchange,提问作者quirimmo

