且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

错误:不变违规:findAllInRenderedTree(...):实例必须是复合组件

更新时间:2022-10-15 08:05:04

这已经很晚了,但我刚刚遇到了这个问题,我还没有找到很好的答案.

我的解决方案是在测试文件中制作一个包装组件

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!