【问题标题】:ReactTestUtils findRenderedComponentWithType throwing error not detecting by chai?ReactTestUtils findRenderedComponentWithType抛出错误没有被chai检测到?
【发布时间】:2016-09-04 15:49:48
【问题描述】:

我使用 findRenderedComponentWithType 来确保有错误,并且我使用 chai 的 assert.throws,但它不起作用。


首先:

TestUtils.findRenderedComponentWithType 文档:

expects there to be one result and returns that one result, or throws exception if there is any other number of matches besides one.


当我使用该功能时,我得到一个错误(如预期和正确)。 但是我似乎不能用 chai 正确地断言它: 我试过assert.throws(TestUtils.findRenderedComponentWithType(element, component), /(Error)/)。但它表示测试失败,即使我收到错误:

 Error: Did not find exactly one match for componentType:function (props, context, updater) {
 [...]
 }

【问题讨论】:

    标签: reactjs mocha.js chai reactjs-testutils


    【解决方案1】:

    检查 throws 的签名,它需要一个函数,而不是错误/对象(这是 findRenderedComponentWithType. http://chaijs.com/api/assert/#method_throws

    所以你会想做类似的事情

    cons fn = () => TestUtils.findRenderedComponentWithType(element, component)
    assert.throws(fn)
    

    【讨论】:

    • 首先谢谢。实际上我以前也读过,但是我没有意识到方法和功能在定义上是不同的,但是我仍然没有真正看到这是如何产生差异的。 chai 不只是运行第一个参数中的任何内容然后检查它输出的内容吗?和回调有关系吗?
    • 您的初始实现没有传入函数(或方法)。它与执行的顺序有关。TestUtils.findRenderedComponentWithType(element, component) 首先执行并返回 Component 对象或引发错误。所以实际上你正在传递其中一种类型。想想它可能如何实施。它接受一个函数,然后将其包装在 try/catch 块中,然后执行它。当你在幕后执行它时,它被包裹起来了,但到那时为时已晚;错误已被抛出
    • 附带说明,您可能需要查看github.com/airbnb/enzyme。我发现 ReactTestUtils 库使用起来有点麻烦(尤其是那些方法名称),所以最终在 Enzyme 可用之前编写了自己的库。
    • 哦,是的,哇,太尴尬了,谢谢。我也一直看到人们在谈论酶,我去看看谢谢!
    猜你喜欢
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多