Redux runSaga(单元测试)错误在局部变量上引发未定义。如何使用Jest或Sinon模拟本地变量?

kis*_*aru 6 sinon jestjs redux-saga

在我的redux saga生成器函数上运行runSaga,我的窗口变量被抛出为undefined,但是我的测试文件通过了,有没有办法模拟窗口变量?

以下是我的redux saga generator函数

import api from 'my-api';
    
const getSuburb = () => window.userCookies.selectedSuburb;

function* saga(payload) {
 const action = yield take('REQUEST_LIBRARY');
 const selectedSuburb = yield call(getSuburb);
 const getStateLibraries = yield call(api.getLibraries, selectedSuburb, action.userId);
 yield put(loadLibrary(getStateLibraries)
}
Run Code Online (Sandbox Code Playgroud)

运行上面的代码后,我收到了有关郊区的库列表,我还有另一个状态保存郊区信息,我可以在其中使用select来检索它。该代码工作正常

单元测试用例以使用RunSaga测试redux saga

const recordSaga = async function (sagaHandler, initalAction) {
  const dispatchedActions = [];
  const fakeStore = {
    getState: () => (initialState),
    dispatch: action => dispatchedActions.push(action),
  };
  await runSaga(
    fakeStore,
    sagaHandler,
    initalAction,
  ).done;
  return dispatchedActions;
};

describe('Run Saga', () => {
 it('should dispatch action libraries', async() => {
  const dispatched = await recordSaga(saga, { user_id:2 });
  expect(dispatched).toContainEqual(loadLibrarySuccess(someProfile));
 }
Run Code Online (Sandbox Code Playgroud)

在运行上面的代码时,selectedSuburb由于未定义window.userCookies.totalSuburbs,所以我无法定义,是否有更好的方法来模拟该getSuburb函数?

kis*_*aru 0

好吧,我已经修改了代码如下,以确保我的测试用例正在运行,但我仍然会寻找完美的解决方案来模拟局部变量

function* saga(payload) {
 const action = yield take('REQUEST_LIBRARY');
 const selectedSuburb = window.userCookies.selectedSuburb
 const getStateLibraries = yield call(api.getLibraries, selectedSuburb, action.userId);
 yield put(loadLibrary(getStateLibraries)
}
Run Code Online (Sandbox Code Playgroud)

我的测试用例看起来像

const recordSaga = async function (sagaHandler, initalAction) {
  const dispatchedActions = [];
  const fakeStore = {
    getState: () => (initialState),
    dispatch: action => dispatchedActions.push(action),
  };
  await runSaga(
    fakeStore,
    sagaHandler,
    initalAction,
  ).done;
  return dispatchedActions;
};

describe('Run Saga', () => {
 it('should dispatch action libraries', async() => {
 const callback = sinon.stub(this, 'userCookies.selectedSuburb');
   callback.onCall(0).returns('suburb_name');
  const dispatched = await recordSaga(saga, { user_id:2 });
  expect(dispatched).toContainEqual(loadLibrarySuccess(someProfile));
 }
Run Code Online (Sandbox Code Playgroud)