redux单元测试Store.dispatch()

时间:2018-05-05 10:19:59

标签: reactjs react-redux karma-jasmine enzyme redux-mock-store

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

import urllib3

medals_url = "http://winterolympicsmedals.com/medals.csv"
http = urllib3.PoolManager()
r = http.request("GET", medals_url)
r.status

data = "".join(map(chr,r.data))
print(data)
data = data.split('\n')
for row in data:
    print(row) # or print(row.split(','))

如何组合这个组件..?

我正在使用带有酵素的业力。 我在下面的代码中写了这个,但这不起作用

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;

我认为这不是商店。

2 个答案:

答案 0 :(得分:1)

首先,你应该provide the store at the top of your app heirarchy

使用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);

在测试中,您可以通过将其作为prop:

将其替换为连接组件
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])
    })
})

答案 1 :(得分: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]);
    })

如果它不能与商店中的间谍合作​​,请在mockedstore和mockedstore.dispatch上尝试间谍