You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jest测试Axios异步函数时then块代码覆盖率未覆盖求助

Fixing Jest Coverage for Redux Async Action's .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.wait to respond to that request, and finally wait for the dispatch promise to resolve before checking actions. This ensures the .then block in getData runs as expected.
  • Reinitialize Store: Creating a new store instance before each test prevents cross-test contamination.
  • Pass Required id: Your getData function expects an id parameter—make sure to pass it when dispatching (I used 1 as an example).
  • Import setData: Ensure setData is imported so expectedActions uses the actual action creator, not an undefined value.

Additional Notes

  • Double-check your getData action for syntax errors: your original code is missing a closing parenthesis in the catch block (should be catch(() => 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.js for collectCoverageFrom settings).

This should resolve the missing coverage for the .then block and make your test more reliable overall.

内容的提问来源于stack exchange,提问作者darKnight

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 15:13:15