CodexBloom - Programming Q&A Platform

Testing a Redux Saga that Makes API Calls scenarios with 'TypeError: how to read properties of undefined'

👀 Views: 83 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-25
redux redux-saga unit-testing jest axios JavaScript

I've been banging my head against this for hours... I've looked through the documentation and I'm still confused about I'm relatively new to this, so bear with me... I'm trying to unit test a Redux Saga that makes an API call using `axios`, but I'm running into a `TypeError: want to read properties of undefined` when I run the test. The saga looks like this: ```javascript import { call, put, takeEvery } from 'redux-saga/effects'; import axios from 'axios'; export function* fetchUser(action) { try { const response = yield call(axios.get, `https://api.example.com/users/${action.payload}`); yield put({ type: 'USER_FETCH_SUCCEEDED', user: response.data }); } catch (e) { yield put({ type: 'USER_FETCH_FAILED', message: e.message }); } } export function* watchFetchUser() { yield takeEvery('USER_FETCH_REQUESTED', fetchUser); } ``` I've set up the test as follows: ```javascript import { runSaga } from 'redux-saga'; import { fetchUser } from './sagas'; import configureMockStore from 'redux-mock-store'; import axios from 'axios'; jest.mock('axios'); const middlewares = []; const mockStore = configureMockStore(middlewares); describe('fetchUser Saga', () => { it('should fetch user successfully', async () => { const dispatched = []; const store = mockStore({}); const userId = 1; const userData = { id: 1, name: 'John Doe' }; axios.get.mockResolvedValue({ data: userData }); await runSaga({ dispatch: (action) => dispatched.push(action) }, fetchUser, { payload: userId }).toPromise(); expect(dispatched).toEqual([{ type: 'USER_FETCH_SUCCEEDED', user: userData }]); }); }); ``` The scenario arises when I run the test and I get the behavior mentioned above. I've verified that `axios` is correctly mocked, and I suspect it might be an scenario with how I'm running the saga or with the parameters being passed. I've tried logging the values and ensuring that everything is defined, but I still need to track down the question. Has anyone else faced this scenario or can suggest what I might be missing? Is there a better approach? Is there a better approach? For context: I'm using Javascript on macOS. I appreciate any insights!