如何在componentWillMount

时间:2018-10-18 15:04:30

标签: reactjs redux jestjs

我有一个React组件,其中在componentWillMount期间通过HTTP获取了一些数据。 这非常类似于使用here所解释的Redux Thunk middleware。 该请求是通过axios完成的。 因此,最初设置为loading状态,并在请求返回时立即设置数据。

class SomeComponent extends Component {
    //...

    componentWillMount() {
        store.dispatch(fetchInitialData())
    }
    // ...
}

执行提取操作:

export function fetchInitialData() {
    return dispatch => {
        return axios.get('https://our.api')
            .then(res => {
                dispatch(handleSuccess(res.data));
            })
            .catch(error => dispatch(handleError(error)));
    }
}

该测试是用Jest和Enzyme编写的,而axios是使用axios-mock-adapter模拟的。

import Enzyme, { mount } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import configureMockStore from 'redux-mock-store'
import Campaigns from './campaigns'
import axios from 'axios'
import MockAdapter from 'axios-mock-adapter'
import thunk from 'redux-thunk'
import response from 'testdata/api/response.json'

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

function createMockStore() {
    const mockStore = configureMockStore([thunk]);
    return mockStore({});
}

describe('some component', () => {
    it('should render ...', () => {
        const mock = new MockAdapter(axios);
        mock.onGet('/our.api').reply(200, response);

        const store = createMockStore();

        const enzymeWrapper = mount(<SomeComponent store={store}/>);

        console.log('enzymeWrapper', enzymeWrapper.html());
    });
});

问题在于enzymeWrapper的html始终仅包含初始状态的表示形式。初始HTML不会根据响应中的新状态进行更改。 当我将日志记录添加到化简器和服务中时,我看到模拟的请求已执行,并且状态充满了模拟的响应。 但是该组件不会使用新的状态数据重新呈现。

我想指出的是,这只是测试中的一个问题。在实际的应用程序中,一切正常。

在我看来,我似乎需要以某种方式等待状态更改得到应用。但是我不知道如何。

0 个答案:

没有答案