簡體   English   中英

使用某些道具(React / Redux)進行連接組件測試

[英]Connected Component testing with certain prop (React/Redux)

我有一個帶有Redux @connect裝飾器的react組件,例如:

import React, { Component } from 'react'
import { connect } from 'react-redux'

@connect(mapStateToProps, 
{
    onPress: () => {...code}) // Component receives this func, not passed from the test
} 
export class Component extends Component {
    render () {
        return <button onclick={this.props.onPress>....</button> 
    }
}

我面臨一個問題,即在測試文件中傳遞給組件的模擬函數未傳遞給組件:

const store = createStore(
    combineReducers({name: reducer})
);
const ComponentConnected = connect(..., {
    onPress: {jest.fn()} // Component doesn't receive this mock
})(() =>(<Component />));

describe('Component testing', () => {
    it('should render component', () => {
        const wrapper = mount(
            <Provider store={store}>
                <ComponentConnected />
            </Provider>
        );
        expect(wrapper.find(Component)).toHaveLength(1);
    });
});

另外,我嘗試將模擬功能作為經過測試的組件道具傳遞,但也沒有幫助。 是否可以在不重寫組件@connect裝飾器的情況下解決此問題?

我認為,不是嘲笑redux-connect的連接功能。 您應該模擬動作本身。 用您的動作文件替換../actions

import { onPress } from "../actions";
jest.mock("../actions");

onPress.mockReturnValue({ someval: 1 });

我發現了如何將道具傳遞給連接的組件。 我使用了淺水,潛水和setProps酶方法:

describe('Component testing', () => {
    it('should render component', () => {
        const wrapper = shallow(
            <Provider store={store}>
                <ComponentConnected />
            </Provider>
        );
        const connectedComponentWrapper = wrapper.dive().dive();
        connectedComponentWrapper.setProps({anyProp: 'anyProp'});
        });
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM