0

我有一个像这样的基本反应组件。

import React from 'react';
import store from 'src/home/store';
class PageLoading extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            message: this.props.message
        };
    }

    componentDidMount(){
        store.dispatch({ type: 'SET_NOTIFICATION_DIALOG', status: '200', message: this.state.message, model: 'LOADING' });
    }

    render(){
        return(<div />);
    }
}


export default PageLoading;

如何统一这个组件..?

我正在使用 karma 和酶。我在下面的代码中写了这个,但这不起作用

import configureMockStore from 'redux-mock-store';
import PageLoading from 'src/home/components/PageLoading';

const middlewares = [];
const mockStore = configureMockStore(middlewares);

Enzyme.configure({ adapter: new Adapter() });

describe("Page Loading",()=>{
    it("testing shoul dispatch action on calling componentdid mount",()=>{
        const initialState = {}
        const store = mockStore(initialState)
        const wrapper = mount(<PageLoading message="loading"/>);
         const actions = store.getActions();
        const expectedPayload = {type: 'SET_NOTIFICATION_DIALOG', status: '200', message:"loading", model: 'LOADING' };
         expect(actions).toEqual([expectedPayload])
    })
})

我认为它没有进入商店。

4

2 回答 2

1

首先,您应该在应用层次结构的顶部提供商店

用于connect连接到商店并注入dispatch您的组件道具:

import React from 'react';
import { connect } from 'react-redux';

class PageLoading extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            message: this.props.message
        };
    }

    componentDidMount(){
        this.props.dispatch({ type: 'SET_NOTIFICATION_DIALOG', status: '200', message: this.state.message, model: 'LOADING' });
    }

    render(){
        return(<div />);
    }
}

export default connect()(PageLoading);

在您的测试中,您可以通过将其作为道具传递来替换连接组件的商店:

describe("Page Loading",()=>{
    it("testing shoul dispatch action on calling componentdid mount",()=>{
        const initialState = {}
        const store = mockStore(initialState)
        const wrapper = mount(<PageLoading store={store} message="loading"/>);
         const actions = store.getActions();
        const expectedPayload = {type: 'SET_NOTIFICATION_DIALOG', status: '200', message:"loading", model: 'LOADING' };
         expect(actions).toEqual([expectedPayload])
    })
})
于 2018-05-05T10:34:28.983 回答
0

试试这个:

it("testing shoul dispatch action on calling componentdid mount",()=>{
        const initialState = {}
        const store = mockStore(initialState)
        const wrapper = mount(<PageLoading message="loading"/>);
         const actions = store.getActions();
        const expectedPayload = {type: 'SET_NOTIFICATION_DIALOG', status: '200', message:"loading", model: 'LOADING' };
        spyOn(store, 'dispatch');

        expect(store.dispatch).toHaveBeenCalledWith([expectedPayload]);
    })

如果它不适用于 spy on store,请尝试 spy on mockedstore 和 mockedstore.dispatch

于 2018-05-05T10:29:25.377 回答