Blog>
Snippets

Mocking Selectors in Saga Tests

Provide an example of mocking selector functions within sagas using the redux-saga-test-plan’s dynamic providers feature.
import { expectSaga } from 'redux-saga-test-plan';
import { select } from 'redux-saga/effects';
import { getUserDetails } from './selectors';
import { fetchUserSaga } from './sagas';

// Mocked user details for testing
const mockedUserDetails = { name: 'John Doe', age: 30 };
First, we're importing necessary utilities from redux-saga-test-plan and redux-saga, alongside the getUserDetails selector we aim to mock, and fetchUserSaga, which is the saga we're testing. We also define mockedUserDetails to simulate the data returned by the selector.
it('successfully fetches user details', () => {
  return expectSaga(fetchUserSaga)
    .provide([
      [select(getUserDetails), mockedUserDetails],
    ])
    .put({ type: 'FETCH_USER_SUCCESS', payload: mockedUserDetails })
    .run();
});
In this test, we're asserting that fetchUserSaga will successfully fetch user details. The .provide method is used to mock the select effect, which will return mockedUserDetails when getUserDetails selector is called within the saga. Then, we expect fetchUserSaga to dispatch a 'FETCH_USER_SUCCESS' action with the mocked user details.