gpt4 book ai didi

javascript - React TestUtils 不适用于装饰器或如何使用 rewire 模拟高阶函数

转载 作者:行者123 更新时间:2023-11-29 14:46:58 28 4
gpt4 key购买 nike

我有一个高阶组件:

import React from 'react';

function withMUI(ComposedComponent) {
return class withMUI {
render() {
return <ComposedComponent {...this.props}/>;
}
};
}

和一个组件:

@withMUI
class PlayerProfile extends React.Component {
render() {
const { name, avatar } = this.props;
return (
<div className="player-profile">
<div className='profile-name'>{name}</div>
<div>
<Avatar src={avatar}/>
</div>
</div>
);
}
}

和使用 React.findDOMNode 的(通过)测试

describe('PlayerProfile', () => {
// profile is type of `withMUI`
let profile = TestUtils.renderIntoDocument(<OkeyPlayerProfile/>);

it('should work', () => {
let elem = React.findDOMNode(profile);

// logs successfully
console.log(elem.querySelectorAll('.player-profile'));
});

// ...
});

和另一个使用 TestUtils 的(失败的)测试:

   // ...
it('should also work', () => {
let elem = TestUtils.findComponentWithTag(profile, 'div');
// throws can't find a match
console.log(elem);
});

如果我删除 @withMUI 装饰器,它将按预期工作。那么,为什么装饰器会影响 TestUtils.findComponentWithTag,我该如何实现呢?

如何模拟 withMUI 函数?使用 babel-plugin-rewire .还是重新布线?

最佳答案

你可以使用 'babel-plugin-remove-decorators' 插件

先安装插件,然后创建一个包含以下内容的文件,我们称之为'babelTestingHook.js'

require('babel/register')({
'stage': 2,
'optional': [
'es7.classProperties',
'es7.decorators',
// or Whatever configs you have
.....
],
'plugins': ['babel-plugin-remove-decorators:before']
});

像下面这样运行你的测试将忽略装饰器,你将能够正常测试组件

mocha ./tests/**/*.spec.js --require ./babelTestingHook.js --recursive

关于javascript - React TestUtils 不适用于装饰器或如何使用 rewire 模拟高阶函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31553167/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com