React中jest.mock不是函数?及如何用Enzyme测试componentDidMount
Hey there! Let's tackle your two React testing issues one by one:
1. Fixing "jest.mock is not a function" Error
This error usually pops up when Jest isn't properly set up in your project, or there's a conflict in your configuration. Here are the most common fixes:
- Ensure Jest is installed correctly: Make sure Jest is a dev dependency in your project. Run this command if you haven't already:
npm install jest --save-dev # or yarn add jest --dev - Check your test script: In your
package.json, confirm your test script points directly to Jest:"scripts": { "test": "jest" } - Avoid conflicting imports: Don't manually import Jest like
import jest from 'jest'— Jest exposes a globaljestobject automatically in test files. Removing any unnecessary imports of Jest can resolve this. - Verify Babel configuration (if using Babel): If you're using Babel, ensure
babel-jestis installed and your Babel config supports Jest's environment. Add this to your Babel config if needed:{ "env": { "test": { "presets": ["@babel/preset-env", "@babel/preset-react"] } } } - For Create React App users: CRA comes with Jest pre-configured. Don't install a separate version of Jest, as this can cause version conflicts. If you've already done so, uninstall the standalone Jest and rely on the CRA-provided one.
2. Testing componentDidMount with Axios using Enzyme
To test that your component fetches data and updates state correctly in componentDidMount, we'll mock Axios (to avoid real network calls) and use Enzyme to mount the component. Here's a step-by-step solution:
Step 1: Mock the Axios module
At the top of your test file, add jest.mock('axios') — this tells Jest to replace the real Axios with a mock version we can control.
Step 2: Write test cases for success and error scenarios
Here's a complete example of the test code:
import React from 'react'; import { shallow } from 'enzyme'; import axios from 'axios'; import List from './List'; // Import your component // Mock the entire axios module jest.mock('axios'); describe('List Component', () => { // Reset mocks between tests to avoid cross-test contamination afterEach(() => { jest.clearAllMocks(); }); it('fetches data and updates state on componentDidMount', async () => { // 1. Define mock response data const mockResponse = { data: { data: ['Todo 1', 'Todo 2'] } }; // 2. Make axios.get resolve with our mock data axios.get.mockResolvedValue(mockResponse); // 3. Mount the component (shallow is fine here, mount works too) const wrapper = shallow(<List />); // 4. Wait for the async axios promise to resolve await Promise.resolve(); // 5. Assert axios.get was called with the correct URL expect(axios.get).toHaveBeenCalledWith('https://*******/getlist'); // 6. Assert the component's state was updated correctly expect(wrapper.state('items')).toEqual(['Todo 1', 'Todo 2']); }); it('handles fetch errors gracefully', async () => { // 1. Define mock error const mockError = new Error('Failed to fetch data'); // 2. Make axios.get reject with our mock error axios.get.mockRejectedValue(mockError); // 3. Spy on console.log to verify the error is logged const consoleLogSpy = jest.spyOn(console, 'log').mockImplementation(); // 4. Mount the component const wrapper = shallow(<List />); await Promise.resolve(); // 5. Assert axios.get was called with the correct URL expect(axios.get).toHaveBeenCalledWith('https://*******/getlist'); // 6. Assert the error was logged expect(consoleLogSpy).toHaveBeenCalledWith(mockError); // Clean up the console.log spy consoleLogSpy.mockRestore(); }); // Optional: Test that componentDidMount is called it('triggers componentDidMount when mounted', () => { const componentDidMountSpy = jest.spyOn(List.prototype, 'componentDidMount'); shallow(<List />); expect(componentDidMountSpy).toHaveBeenCalled(); // Clean up the spy componentDidMountSpy.mockRestore(); }); });
Key Notes:
- Avoid real network calls: Mocking Axios ensures your tests are fast and don't depend on external services.
- Async handling: Using
await Promise.resolve()waits for all pending promises (like the Axios call) to resolve before making assertions. - Mock cleanup: Using
jest.clearAllMocks()inafterEachensures mocks don't retain state between tests. - Spy cleanup: Always restore spies (like the
console.logorcomponentDidMountspy) to avoid affecting other tests.
内容的提问来源于stack exchange,提问作者naveen
相关产品推荐
相关产品推荐

