Jest测试Axios异步函数时then块代码覆盖率未覆盖求助
.then Block I see the issue here—your test's execution flow is out of order, which is why the .then block in your getData action isn't being picked up by coverage reports. Let's break down what's wrong and how to fix it:
Root Cause
In your test, you're calling store.dispatch(getData()) inside the moxios.wait callback. But moxios.wait is designed to run after a request has been initiated. By dispatching the action inside this callback, you're creating a race condition where the request isn't being made before you try to respond to it, leading to the .then block in your action never properly executing (even though the test might seem to pass due to Jest's loose timing).
Corrected Test Code
Here's the fixed version of your test, with comments explaining the proper flow:
import configureMockStore from "redux-mock-store"; import thunk from "redux-thunk"; import moxios from "moxios"; import getData from '../redux/getData'; import { setData } from '../redux/actions'; // Make sure to import setData! const middlewares = [thunk]; const mockStore = configureMockStore(middlewares); describe('Test fetch data', () => { let store; beforeEach(function() { moxios.install(); store = mockStore({}); // Reinitialize store before each test store.clearActions(); }); afterEach(function() { moxios.uninstall(); }); it('should fetch data and set it', () => { const data = [{ name: 'John', profession: 'developer'}]; const expectedActions = [setData(data)]; // 1. First, dispatch the async action to trigger the API request const dispatchPromise = store.dispatch(getData(1)); // Pass an id (your action expects it!) // 2. Wait for the request to be made, then respond with mock data moxios.wait(() => { const request = moxios.requests.mostRecent(); request.respondWith({ status: 200, response: data }); }); // 3. Wait for the dispatch promise to resolve, then assert actions return dispatchPromise.then(() => { expect(store.getActions()).toEqual(expectedActions); }); }); });
Key Fixes Explained
- Proper Execution Order: We first dispatch the action to initiate the request, then use
moxios.waitto respond to that request, and finally wait for the dispatch promise to resolve before checking actions. This ensures the.thenblock ingetDataruns as expected. - Reinitialize Store: Creating a new store instance before each test prevents cross-test contamination.
- Pass Required
id: YourgetDatafunction expects anidparameter—make sure to pass it when dispatching (I used1as an example). - Import
setData: EnsuresetDatais imported soexpectedActionsuses the actual action creator, not an undefined value.
Additional Notes
- Double-check your
getDataaction for syntax errors: your original code is missing a closing parenthesis in thecatchblock (should becatch(() => alert('Could not fetch data'));). - If you still have coverage issues, verify that Jest is correctly configured to include your action files in coverage reports (check your
jest.config.jsforcollectCoverageFromsettings).
This should resolve the missing coverage for the .then block and make your test more reliable overall.
内容的提问来源于stack exchange,提问作者darKnight

