【问题标题】:Testing throw error inside generator?测试生成器内的抛出错误?
【发布时间】:2016-12-29 15:05:21
【问题描述】:

我正在尝试使用 Jest 和 Chai 测试生成器函数中引发的错误,如下所示:

    // function

    function * gen () {
        yield put({ type: TIME_OUT_LOGOUT })
        throw new Error('User has logged out')
    }

    //test

    let genFunc = gen()

    expect(genFunc().next).to.deep.equal(put({ type: TIME_OUT_LOGOUT }))

    expect(genFunc().next).to.throw(Error('User has logged out'));

但它不起作用。哪种方法是正确的测试方法?

【问题讨论】:

    标签: javascript testing redux generator redux-saga


    【解决方案1】:

    尝试将您的测试代码从 genFunc().next 更改为 genFunc.next().value


    编辑:

    断言应该是:

    expect(genFunc.next().value).toEqual(put({type: TIME_OUT_LOGOUT})); expect(genFunc.next).toThrow(Error);

    对于第二个断言expect(() => genFunc.next()).toThrow(Error); 也可以,但是包装函数() => genFunc.next() 是不必要的,因为genFunc.next 不接受任何参数。

    【讨论】:

    • 它似乎不起作用,这实际上是有道理的,因为生成器函数没有其他 next.value,因为没有其他 yield。
    • 你的第一个断言有效吗?无论如何,我已经进行了更正。以下对我有用(使用 Jasmine 语法):expect(genFunc.next().value).toEqual(put({ type: TIME_OUT_LOGOUT })); expect(() => genFunc.next()).toThrow(Error('User has logged out'));注意第二个断言中 genFunc.next() 周围的包装函数。
    • 好吧,我搞定了,把断言改成:expect(genFunc.next().value).toEqual(put({ type: TIME_OUT_LOGOUT }));期望(() => genFunc.next()).toThrow(错误);如果您想发布答案,我可以将其标记为解决方案。非常感谢!
    • 很高兴能帮上忙
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-15
    • 2020-07-24
    • 2016-03-14
    • 2021-04-03
    • 2012-11-21
    • 2020-12-07
    相关资源
    最近更新 更多