说我在Index.tsx
上有以下内容:
ReactDOM.render(
<h2 style={{textAlign: "center"}}>Hello World</h2>,
document.getElementById("wrapper")
);
首先,我如何对ReactDOM.render
电话进行单元测试?其次,在Karma + PhantomJS上运行它,我收到以下错误:
不变违规: _registerComponent(...):目标容器不是DOM元素。
at /tmp/karma-typescript-bundle-192osSfGKwYIxIW.js:188
这是因为document.getElementById("wrapper")
在PhantomJS下不起作用,因为没有wrapper
元素。
解决这个问题的最佳方法是什么?反正我是否可以在PhantomJS上插入/模拟wrapper
元素一次?
答案 0 :(得分:2)
如果DOM中没有#wrapper
元素,则必须创建它并在运行特定测试之前准备环境。您可以使用jsdom帮助您在测试之间创建和维护DOM。
React有一个用于编写单元测试的官方包,称为react-addons-test-utils
。它使您可以轻松地在您选择的测试框架中测试React组件。
更多信息可在官方文档中找到:https://facebook.github.io/react/docs/test-utils.html
我建议你另一个解决方案。 Airbnb已发布Enzyme,这使得编写单元测试非常容易。 API有很好的文档记录和直接的。在测试实用程序 - React文档中甚至有关于酶的信息。
Airbnb has released a testing utility called Enzyme,
which makes it easy to assert, manipulate, and traverse your React
Components' output. If you're deciding on a unit testing utility to
use together with Jest, or any other test runner,
it's worth checking out: http://airbnb.io/enzyme/
在Github上,您可以找到几乎每个测试框架的启动器,甚至还有starter for Karma with sample repositories。
最后一件事是,如果您决定使用jsdom
,react-addons-test-utils
或enzyme
,则不再需要PhantomJS
,因为您的所有测试都可以只在Node.js中运行,这将使你的测试更快。
这是每个工具作为开发人员提供的解释:
请记住,像Jasmine这样的测试框架也为您提供了一些模拟功能,因此您不需要Sinon。
您可以将enzyme
与任何测试运行器和框架一起使用。
你可以将它与Karma和Jasmine一起使用。
你可以将它与摩卡一起使用。
你可以和Jest一起使用它。
有很多测试框架和运行者;)