Redux Store在测试用例中共享

时间:2018-01-25 07:44:40

标签: reactjs redux react-redux

我有一个类似于这样的util类:

    mountGk = (component, appReducer) => {
        let store = createStore(appReducer);
        return [
            mount(
                    <Provider store={store}>
                    {intl(component)}
                    </Provider>
                 ),
            store
        ];
    }
}

它用在我的mocha测试用例中:

        const component = (
            <SelectUsers input={input}/>
        );
        [wrapper, store] = mountGk(component, appReducer);

假设我有两个使用mountGk的测试用例。在其中一个中,我修改了这样的状态:

store.getState()['some']['state']= ['1', '2']

现在问题是我在另一个测试用例中看到相同的值[&#39; 1&#39;,&#39; 2&#39;],即使我没有设置它。

我现在关注的是createStore不是线程安全的。如果是这样,我就无法为我的React应用程序编写测试用例。请帮忙。

2 个答案:

答案 0 :(得分:0)

首先,你不应该像那样修改你的状态。状态永远不会直接在Redux中修改,当然也不能通过调用 get 状态来修改。要修改状态,请分派操作。

如果您在同一个套件中的两个测试中使用相同的状态,那是因为您没有再次调用每个测试中的mountGk函数,您应该这样做

每次测试都应该有一个清新的环境!因为您的功能会重新创建商店,所以每次调用它都会得到一个新商店。

如果要在测试之间重用变量名称,请使用以下内容:

let store, wrapper

beforeEach(() => {
  const [newStore, newWrapper] = mountGk(...)
  store = newStore
  wrapper = newWrapper
})

it('does something', () => {
  store.dispatch(...)
})

答案 1 :(得分:0)

我找到了答案。实际上问题是因为我修改了没有传播操作符(或创建新对象)的状态。解决方案:

            let iState = store.getState()['some'];
            iState = {
                ...iState,
                state: ['1', '2']
            };
            store.getState()['some'] = iState;

说明:store.getState()[&#39; some&#39;]实际上是我的一个reducer函数的关键。现在,reducer函数看起来像这样。

const initialState = {
    users: []
};

const ga_food_upload = (state= initialState, action) => {
// some code
}

这意味着当你做store.getState()[&#39;某些&#39;] [&#39;州&#39;] = [&#39; 1&#39;,&#39; 2&# 39;],您实际上更改了const变量initialState,这会影响其他测试用例。