我想快照测试一个反应组件,它在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