javascript - 用 jest + 酶 + react-redux 测试 propTypes 的最佳实践?
问题描述
我已经尝试了很多我在谷歌上找到的解决方案来测试是否Component.propTypes
在反应组件中正确设置,但没有一个对我有用。如果属性传递不正确,即使在浏览器上运行我的 React 应用程序时会收到控制台警告,但当我运行 jest 时,我无法以我尝试的任何方式捕获该警告。这是我最好的尝试:
应用程序.js:
export class App extends Component {
constructor(props) {
super(props);
}
render() {
return <div/>;
}
}
App.propTypes = {
images: PropTypes.array.isRequired
};
function mapStateToProps(state) {
const {images} = state;
return {images: images};
}
export default connect(mapStateToProps)(App);
应用程序.test.js:
import React from 'react';
import chai from 'chai';
import chaiEnzyme from 'chai-enzyme';
import {shallow} from 'enzyme';
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import sinon from 'sinon'
import {Provider} from 'react-redux';
import App from './App';
const expect = chai.use(chaiEnzyme()).expect
const mockStore = configureStore([thunk]);
const wrap = (initialState, props) => {
return shallow(<Provider store={mockStore(initialState)}><App {...props} /></Provider>)
};
describe('App container', () => {
it('validates properties', () => {
const stub = sinon.stub(console, 'warn');
console.warn.reset();
React.createElement(App, {});
expect(stub.calledOnce).to.equal(true);
expect(stub.calledWithMatch(/Failed prop type/)).to.equal(true);
console.warn.restore();
});
it('renders without crashing', () => {
wrap();
});
it('is react-redux connected', () => {
const wrapper = wrap();
expect(wrapper.find('Connect(App)')).to.have.length(1);
});
it('correctly maps properties', () => {
const wrapper = wrap({images: []});
expect(wrapper.props().images).to.equal([]);
});
});
解决方案
根据我在各种 GitHub 问题线程上在线阅读的内容,似乎一种常见的方法是console.warn/console.error
抛出。
因此,当您编写测试时,您可以执行类似的操作
expect(// Render Component //).to.throw();
希望这可以帮助。
推荐阅读
- tableau-api - 如何在每一行的画面中显示饼图
- python - 在plot.ly-Dash隐藏Div中存储熊猫数据框字典?
- html - 如何检索动态框值(如果选中,则为真或假) - Angular 6
- react-admin - 在 API 平台管理员中保存为数组
- sql - 获取字符串的数字部分后前导零
- mysql - 两列sql之间的两次
- php - 您可以通过字符串中的名称获取变量的值吗?
- cordova - MobileFirst Cordova resolveLocalFileSystemURL() 抛出错误代码 5
- python - 导入错误:没有名为 xxxxxx 的模块,但有一个名为 xxxxxxx 的模块
- r - 从列中选择不同的值并在 R 中相应地写入值