2016-05-09 19 views
0

我使用findRenderedComponentWithType来确保有错误,并使用chai的assert.throws,但它不工作。ReactTestUtils findRenderedComponentWithType抛出错误没有通过柴检测?


首先:

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) { 
[...] 
} 

回答

1

检查抛出的签名,它期望的功能,而不是错误/物件(这是findRenderedComponentWithType结果 http://chaijs.com/api/assert/#method_throws

所以,你会想要做类似

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

首先它工作的感谢。其实我读了之前,但我却没有意识到方法和功能是通过定义不同,但我仍然不真的看到这是如何做出差异。没有柴只是运行在第一个参数,然后检查它输出什么?它与回调有什么关系? – user308553

+1

您的初始实现未传入函数(或方法)。它与执行事务的顺序有关。'TestUtils.findRenderedComponentWithType(element,component)'被首先执行并返回一个Component对象或者抛出一个错误。所以你真的会传入其中的一种类型。 想想它是如何实现的。它接受一个函数,然后将它封装在一个try/catch块中,然后执行它。而你正在执行它,那么在幕后它正在被包裹,但是到那时为时已晚。错误已被抛出 – ken4z

+1

作为一个方面说明,你可能想看看https://github.com/airbnb/enzyme。我发现ReactTestUtils库在处理(特别是那些方法名称)时有点痛苦,所以最终在Enzyme变得可用之前写下了我自己的。 – ken4z