React项目中Index.js测试用例编写及测试覆盖率问题求助
First, let's fix a small but critical syntax issue in your index.js that's likely causing errors right now: the component tags have incorrect spacing. <Component 1/> should be <Component1 /> (no space between the component name and its suffix), same for <Component 2/> → <Component2 />. Here's the corrected code:
import React from 'react'; import ReactDOM from 'react-dom'; import Component1 from './Components/Component1'; import Component2 from './Components/Component2'; if (navigator.userAgent.toLowerCase().indexOf('Chrome') > -1) { ReactDOM.render(<Component1 />, document.getElementById('app')); } else { ReactDOM.render(<Component2 />, document.getElementById('app')); }
Now, let's tackle testing this logic with React Testing Library. The core challenge here is mocking the navigator.userAgent property to simulate different browsers, then verifying which component gets rendered.
Step 1: Set up your test file
Create a test file (e.g., index.test.js) in the same directory as your index.js. We'll use React Testing Library alongside Jest for mocking and assertions.
Step 2: Mock components and test each browser scenario
We need to override navigator.userAgent before each test and reset it afterward to avoid cross-test contamination. Here's a complete test implementation:
import React from 'react'; import { render, screen } from '@testing-library/react'; import './index'; // Import the index file which triggers rendering import Component1 from './Components/Component1'; import Component2 from './Components/Component2'; // Mock both components to simplify verification jest.mock('./Components/Component1', () => ({ __esModule: true, default: () => <div data-testid="component-1" />, })); jest.mock('./Components/Component2', () => ({ __esModule: true, default: () => <div data-testid="component-2" />, })); describe('index.js browser-specific rendering', () => { // Store original userAgent to restore after all tests const originalUserAgent = navigator.userAgent; beforeEach(() => { // Reset the DOM with the required #app element before each test document.body.innerHTML = '<div id="app"></div>'; }); afterAll(() => { // Restore original userAgent to avoid affecting other tests Object.defineProperty(navigator, 'userAgent', { value: originalUserAgent, writable: false, }); }); test('renders Component1 when userAgent contains Chrome', () => { // Mock a Chrome userAgent string Object.defineProperty(navigator, 'userAgent', { value: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36', writable: true, }); // Require the index file again to trigger rendering with the mocked userAgent require('./index'); // Verify Component1 is present and Component2 is not expect(screen.getByTestId('component-1')).toBeInTheDocument(); expect(screen.queryByTestId('component-2')).not.toBeInTheDocument(); }); test('renders Component2 when userAgent does NOT contain Chrome', () => { // Mock a non-Chrome userAgent (e.g., Firefox) Object.defineProperty(navigator, 'userAgent', { value: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/114.0', writable: true, }); // Require the index file again for this test scenario require('./index'); // Verify Component2 is present and Component1 is not expect(screen.getByTestId('component-2')).toBeInTheDocument(); expect(screen.queryByTestId('component-1')).not.toBeInTheDocument(); }); });
Key Details to Note:
- Mocking Components: We mock
Component1andComponent2to return simple divs with unique test IDs. This lets us easily check which component renders without relying on the actual component's internal content. - Overriding
navigator.userAgent: UsingObject.definePropertylets us modify the normally read-onlynavigator.userAgentproperty for our tests. - Resetting the DOM: Before each test, we recreate the
#appelement since your index.js targets this element for rendering. - Requiring the Index File: Since the rendering logic runs immediately when the index file is imported, we need to require it after setting up the mock userAgent for each test to ensure the correct component renders.
Quick Note for React 18 Users:
If your index.js uses createRoot instead of ReactDOM.render, the testing approach stays almost identical—you just need to ensure your mock setup and assertions align with the new rendering API.
内容的提问来源于stack exchange,提问作者dinesh

