【问题标题】:Error [object Object] thrown抛出错误 [object Object]
【发布时间】:2018-06-19 20:04:38
【问题描述】:

我遇到了这个问题,并且后来发现了这个问题,但作为其他用户的文档,我在这里发布了我发现的内容。另请注意,经验丰富的 JS 开发人员可能已经了解我的错误所在,这仅适用于像我这样的 JS 新手。

我有一个类似这样的传奇:

   function* patchCart({ payload: { data, sections } }) {
      const current = yield select(cartSelectors.getCartModel);
      const oldAttributes = pick(current, keys(data));

      try {
        yield call(patchCartTry, data, sections);
      } catch (error) {
        yield call(patchCartError, error, oldAttributes);
      }
    }

在我的测试中,我试图测试 saga 的 catch 块。我的部分测试代码如下所示:

    let current = iterator.next().value;
    expect(current).toEqual(select(cartSelectors.getCartModel));

    current = iterator.throw(error).value;
    expect(current).toEqual(call(utilities.patchCartCatch, error, oldAttributes));

运行测试的结果给出了类似的输出:

Error
    [object Object] thrown

在整个互联网上都找不到答案,我遇到的每个人都有这个问题,他们的错误是由于没有在他们的迭代器上调用 .next() 引起的 - 我已经在这样做了。

即使在 catch 块中的 saga 内部登录也没有触发,所以我知道测试从未真正进入那里。

请继续关注答案和后续解释。

【问题讨论】:

    标签: javascript react-native jestjs redux-saga


    【解决方案1】:

    问题是,当我调用 .next() 时,我调用的次数不够多。

    我读过的所有资源都说您需要调用 .next() 才能进入生成器函数,但没有人提到您需要在调用 .throw(error) 之前调用它的原因是您需要迭代您的函数进入try 块。测试的行为与应有的完全一样,您在 try/catch 之外引发了异常,因此测试引发了错误。

    所以要修复我的测试,我必须将其更改为:

        let current = iterator.next().value;
        expect(current).toEqual(select(cartSelectors.getCartModel));
    
        current = iterator.next().value;
        expect(current).toEqual(call(utilities.patchCartTry, data, sections));
    
        current = iterator.throw(error).value;
        expect(current).toEqual(call(utilities.patchCartCatch, error, oldAttributes));
    

    从而确保我在try 块内,然后抛出异常,将我带入我的catch 块。

    因为这个启示的功劳 - 对我来说是一个启示 - 是由于其他人,这里是帮助我解决这个问题的评论的链接。 github issue comment

    【讨论】:

      猜你喜欢
      • 2014-02-26
      • 2018-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多