我想快照測試一個反應組件,它在componentDidMount()
處理程序中分派一個redux動作。該操作通過Redux的connect()
提供給組件。如何使用Redux connect中的操作快照測試組件?
我該如何嘲笑這個動作?
現在的動作是在組件的進口(見下文Newsfeed.js)。那麼,如何將我的測試中的模擬動作換掉?
我使用的終極版,形實轉換爲我的異步操作,但應該沒有多大關係。
應用程序/組件/ Newsfeed.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
// An action that makes an async request to get data
import { loadNewsfeedStories } from '../actions/Newsfeed';
class Newsfeed extends Component {
componentDidMount(){
this.props.loadNewsfeedStories();
}
...
}
export default connect(state => ({
stories: state.newsfeed.stories
}),
{
loadNewsfeedStories
})(Newsfeed)
應用程序/測試/ Newsfeed.test.js
import React from 'react';
import { Provider } from 'react-redux';
// This creates a mockStore using my reducers and a saved JSON state.
import { mockStore } from './MockState';
// The component to test
import Newsfeed from '../components/Newsfeed';
test('Newsfeed matches snapshot',() => {
const wrapper = mount(
<Provider store={mockStore}>
<Newsfeed />
</Provider>
);
expect(wrapper).toMatchSnapshot();
});
可能的解決方案
導出未連接的組件,並手動傳遞所有道具&模擬操作。與僅使用mockStore &提供者相比,將會有很多額外的編碼。我們也不會測試'連接'組件。
使用類似Nock?似乎攔截HTTP調用,所以Ajax請求實際上不會去任何地方。
對於愛可信,有一個lib稱爲moxios - https://github.com/mzabriskie/moxios