Redux Saga,为什么在从包含胖箭头函数的文件中对 saga 进行单元测试时收到错误?

Redux Saga, why do I receive an error when unit testing a saga from a file containing a fat arrow function?

我在尝试从 redux saga 测试 saga 时遇到了以下情况。

部分包裹信息:

我使用 redux-saga@0.15.6redux@3.7.2node v9.5.0npm 5.6.0

我有以下结构:

sagas
    index.js
    index.spec.js

index.js 中,我定义了我的传奇。我所拥有的一个基本想法是:

function doSomething() {
  /* Some code */
}

function* notExportedSaga() {
  yield takeLatest(SOME_ACTION, doSomething)
}

export function* exportedSaga(action) {
  yield put({ type: OTHER_ACTION, payload: somePayload })
}

index.spec.js,我想测试我的sagas。我的文件顶部有一个 import

import { exportedSaga } from './index'

使用我描述的结构和代码,这工作得很好。但是,如果我将 doSomething 从被定义为一个粗箭头函数:

const doSomething = () => {
  /* Some code */
}

会发生什么,当运行单元测试时,我会得到这个错误:

console.error node_modules/redux-saga/lib/internal/utils.js:240
  uncaught at rootSaga
   at rootSaga
   at rootSaga
   ReferenceError: doSomething is not defined

你知道为什么会这样吗?


我已经打开了一个issue ,因为我不知道这是不是一个错误。

函数声明喜欢

function doSomething() { }

正在提升到顶部

函数表达式喜欢

const doSomething = () => { }

没有被提升

这就是你得到 doSomething is not defined 的原因 - notExportedSagaexportedSaga 函数都被提升到顶部,而表达式函数 const doSomething = () => { } 不是,它是在您的生成器函数调用中未定义。

如果您想了解更多,这里有一篇关于 hoisting 的精彩文章:) https://scotch.io/tutorials/understanding-hoisting-in-javascript