【问题标题】:TestUtils.renderIntoDocument return null, if it declared as anonymous function如果 TestUtils.renderIntoDocument 声明为匿名函数,则返回 null
【发布时间】:2016-11-14 20:47:10
【问题描述】:

我有 2 种代码变体:

FIRST(声明为类):

export default class COMPONENT_NAME extends React.Component{
    constructor(props){
    super(props);
    this.props = props;
    }
    ....
    render = () => <div className="clName"></div>
}

SECOND(声明为匿名函数):

export default (props) => <div className="clName"></div>

笑话代码:

jest.dontMock('../js/components/COMPONENT_NAME/index');
const COMPONENT_NAME = require('../js/components/COMPONENT_NAME/index.js').default;
var loaderComponent;
...
...
function renderComponent() {
    loaderComponent = TestUtils.renderIntoDocument(
    <COMPONENT_NAME />
    );
}

为什么测试只在第一种情况下有效?

在第二种情况下,renderIntoDocument 返回 null。 我找不到任何有关它的信息。

所以问题是 - JEST 是否支持渲染匿名函数?

【问题讨论】:

    标签: javascript reactjs testing jestjs


    【解决方案1】:

    尝试改变

    jest.dontMock('../js/components/COMPONENT_NAME/index');
    

    到

    jest.unmock('../js/components/COMPONENT_NAME/index');
    

    【讨论】:

    • 面临完全相同的问题。尝试 unmock 而不是 dontMock 但不起作用。
    【解决方案2】:

    你应该将你的功能组件包装到div中,当它传递给TestUtils.renderIntoDocument函数时:

    function renderComponent() {
        loaderComponent = TestUtils.renderIntoDocument(
            <div>
                <COMPONENT_NAME />
            </div>
        );
    }
    

    【讨论】:

    • 已经试过了,不帮忙:Invariant Violation: findAllInRenderedTree(...): instance must be a complex component
    猜你喜欢
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-25
    • 1970-01-01
    相关资源
    最近更新 更多