Redux Saga:抛出并停止生成器
Redux Saga: Throw and stop generator
我正在写一个生成器。我正在用 RITEway 测试它。它检查是否定义了 window.ethereum
。如果不是,它应该抛出并停止。基本上应该满足以下测试:
describe('handle initialize Web3 saga', async assert => {
global.window = {}
assert({
given: 'nothing, the window object',
should: 'have no property called Web3',
actual: window.web3,
expected: undefined
})
const gen = cloneableGenerator(handleInitializeWeb3)()
{
// The important parts are in this block scope
const clone = gen.clone()
assert({
given: 'window.ethereum undefined',
should: 'throw',
actual: clone.next().value.message,
expected: '[WARNING]: window.ethereum has no provider!'
})
assert({
given: 'nothing',
should: 'be done',
actual: clone.next().done,
expected: true
})
}
class Provider {}
window.ethereum = new Provider()
// ... more tests
})
以下是我尝试实现它的方法。
function* handleInitializeWeb3() {
if (!window.ethereum) {
yield new Error('[WARNING]: window.ethereum has no provider!')
}
// ... more yields
}
但是这个传奇并没有停止。 should: 'be done'
失败的测试,传奇从 if
语句之外的 yield
s 返回值。我怎样才能让这些测试通过并在抛出错误时停止 saga?
yield
ing 错误实例的行为与产生任何其他值的行为相同(即生成器保持 运行)。如果你想停止生成器,你应该像在正常函数中一样throw new Error(...
。
如果出于某种原因您不想 throw
而实际上想要产生一个错误实例然后停止,只需 return;
在您 yield
ed 之后错误。
我正在写一个生成器。我正在用 RITEway 测试它。它检查是否定义了 window.ethereum
。如果不是,它应该抛出并停止。基本上应该满足以下测试:
describe('handle initialize Web3 saga', async assert => {
global.window = {}
assert({
given: 'nothing, the window object',
should: 'have no property called Web3',
actual: window.web3,
expected: undefined
})
const gen = cloneableGenerator(handleInitializeWeb3)()
{
// The important parts are in this block scope
const clone = gen.clone()
assert({
given: 'window.ethereum undefined',
should: 'throw',
actual: clone.next().value.message,
expected: '[WARNING]: window.ethereum has no provider!'
})
assert({
given: 'nothing',
should: 'be done',
actual: clone.next().done,
expected: true
})
}
class Provider {}
window.ethereum = new Provider()
// ... more tests
})
以下是我尝试实现它的方法。
function* handleInitializeWeb3() {
if (!window.ethereum) {
yield new Error('[WARNING]: window.ethereum has no provider!')
}
// ... more yields
}
但是这个传奇并没有停止。 should: 'be done'
失败的测试,传奇从 if
语句之外的 yield
s 返回值。我怎样才能让这些测试通过并在抛出错误时停止 saga?
yield
ing 错误实例的行为与产生任何其他值的行为相同(即生成器保持 运行)。如果你想停止生成器,你应该像在正常函数中一样throw new Error(...
。
如果出于某种原因您不想 throw
而实际上想要产生一个错误实例然后停止,只需 return;
在您 yield
ed 之后错误。