TestUtils.renderIntoDocument返回null,如果它声明为匿名函数

时间:2016-07-12 14:30:42

标签: javascript reactjs testing jestjs

我有两种代码变体:

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 CODE:

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是否支持渲染匿名函数?

2 个答案:

答案 0 :(得分:1)

尝试更改

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

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

答案 1 :(得分:-1)

在将功能组件传递给div函数时,应将其包装到TestUtils.renderIntoDocument中:

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