【问题标题】:Best practice to test propTypes with jest + enzyme + react-redux?用 jest + 酶 + react-redux 测试 propTypes 的最佳实践?
【发布时间】:2019-01-07 22:20:07
【问题描述】:

我尝试了很多我在谷歌上找到的解决方案来测试 Component.propTypes 是否在反应组件中正确设置,但没有一个对我有用。如果属性传递不正确,即使在浏览器上运行我的 React 应用程序时会收到控制台警告,但当我运行 jest 时,我无法以我尝试的任何方式捕获该警告。这是我最好的尝试:

App.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);

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([]);
    });
});

【问题讨论】:

标签: javascript reactjs react-redux jestjs enzyme


【解决方案1】:

根据我在各种 GitHub 问题线程上在线阅读的内容,似乎一种常见的方法是让console.warn/console.error 抛出。

因此,当您编写测试时,您可以执行类似的操作

expect(// Render Component //).to.throw();

希望这会有所帮助。

更多信息:https://github.com/airbnb/enzyme/issues/588

【讨论】:

    猜你喜欢
    • 2021-12-09
    • 2022-12-01
    • 2021-10-26
    • 2021-08-19
    • 2017-05-03
    • 1970-01-01
    • 2019-03-22
    • 2020-07-15
    • 2014-11-25
    相关资源
    最近更新 更多