首页 > 解决方案 > 用 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([]);
    });
});

标签: javascriptreactjsreact-reduxjestjsenzyme

解决方案


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

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

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

希望这可以帮助。

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


推荐阅读