在我的redux saga生成器函数上运行runSaga时,我的窗口变量被抛出为未定义,但是我的测试文件正在通过,有没有办法模拟窗口变量?
下面是我的redux saga生成器函数
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)
}
运行上述代码后,我收到了有关郊区的图书馆列表,我还有另一个州保存郊区信息,我可以在其中使用select来检索它。代码工作正常
使用RunSaga测试Redux传奇的单元测试用例
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));
}
运行上述命令时,我未定义selectedSuburb
,因为未定义window.userCookies.totalSuburbs,有没有更好的方法来模拟数据?或测试佐贺的任何首选方法
好的,我已经修改了以下代码,以确保我的测试用例正在运行
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)
}
我的测试用例看起来像
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));
}