错误:不变违规:findAllInRenderedTree(...):实例必须是复合组件 [英] Error: Invariant Violation: findAllInRenderedTree(...): instance must be a composite component
问题描述
在 JEST 中为 React 文件编写测试用例时,出现此错误.以下是我的示例代码:
search_basr_test.js
jest.autoMockOff();global.React = require('react/addons');jest.setMock('../stores/browser_store.jsx');beforeEach(函数(){var search_bar = require('../components/search_bar.jsx');});var TestUtils = React.addons.TestUtils;描述(测试",函数(){它(应该渲染测试",函数(){var test = TestUtils.renderIntoDocument( );期望(测试).toBeDefined();});it("在具有适当 CSS 类的框中呈现列表", function() {var test = TestUtils.renderIntoDocument( );让 box = TestUtils.findRenderedDOMComponentWithTag(test, "div");期望(box.className).toEqual("sidebar__collapse");});});
search_bar.jsx
返回(<div><跨度类名='搜索__清除'onClick={this.clearFocus}>{'取消'}</span>}
有人能帮我解决这个问题吗??
这已经很晚了,但我刚刚遇到了这个问题,我还没有找到很好的答案.
我的解决方案是在测试文件中制作一个包装组件
import { Component } from "react";类 Wrapper 扩展组件 {使成为() {返回 <YourComponent {...this.props}/>}}
而不是调用
TestUtils.renderIntoDocument(<你的组件/>);
打电话
TestUtils.renderIntoDocument(<包装/>);
这样做可以确保您的组件是一个复合组件,而不是一个无状态函数.
希望这对未来的其他人有所帮助!
While writing the test case in JEST for React file I am getting this error. Following is my sample code:
search_basr_test.js
jest.autoMockOff();
global.React = require('react/addons');
jest.setMock('../stores/browser_store.jsx');
beforeEach(function() {
var search_bar = require('../components/search_bar.jsx');
});
var TestUtils = React.addons.TestUtils;
describe("Test", function() {
it("should render Test", function() {
var test = TestUtils.renderIntoDocument(<search_bar/>);
expect(test).toBeDefined();
});
it("renders a list in a box with proper CSS classes", function() {
var test = TestUtils.renderIntoDocument(<search_bar/>);
let box = TestUtils.findRenderedDOMComponentWithTag(test, "div");
expect(box.className).toEqual("sidebar__collapse");
});
});
search_bar.jsx
return (
<div>
<div
className='sidebar__collapse'
onClick={this.handleClose}
>
<span className='fa fa-angle-left'></span>
</div>
<span
className='search__clear'
onClick={this.clearFocus}
>
{'Cancel'}
</span>
}
Anyone out there to help me out from this??
This is late, but I just ran into this, and I haven't found a great answer for it.
My solution was to make a wrapper component in the test file
import { Component } from "react";
class Wrapper extends Component {
render() {
return <YourComponent {...this.props} />
}
}
and instead of calling
TestUtils.renderIntoDocument(
<YourComponent />
);
call
TestUtils.renderIntoDocument(
<Wrapper />
);
Doing this ensures that your component is a composite component and isn't a stateless function.
Hope this helps anyone else in the future!
这篇关于错误:不变违规:findAllInRenderedTree(...):实例必须是复合组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!