这是我的Redux / React组件的精简版本:
import React from "react";
import { connect } from "react-redux";
import Header from "./components/Header";
import { getMoviesInit } from "./actions/movieActions";
export class Layout extends React.Component {
componentWillMount() {
if (this.props.movies.length == 0) {
this.props.dispatch((dispatch) => {
dispatch(getMoviesInit());
});
}
}
render() {
return (
<div id="content-wrap">
<Header/>
{this.props.children}
</div>
);
}
};
export default connect((store) => {
return {
movies: store.movies
};
})(Layout);
当我尝试运行如下所示的测试时,我告诉我this.props.dispatch()isn&#39; ta函数是有意义的,因为在componentWillMount()中有一个dispatch()调用函数和我没有使用connect()包装的布局:
import React from "react";
import LayoutWithConnect, { Layout } from "./Layout";
import { mount, shallow } from 'enzyme';
import { expect } from 'chai';
describe("Layout tests", function() {
beforeEach(() => {
let movies = {
featuredId: null,
currentTitles: {
movies: []
}
};
let subject = shallow(<Layout movies={movies} />);
});
});
但是,如果我在测试中尝试使用LayoutWithConnect,那么就会出现没有商店的问题。
我不确定如何测试这个组件?
答案 0 :(得分:1)
您可以简单地将dispatch
函数作为道具传递:
let dispatchedAction;
let dispatch = (action) => dispatchedAction = action;
let subject = shallow(<Layout movies={movies} dispatch={dispatch} />);
然后,您还可以通过将dispatchedAction
与预期的操作对象进行比较来测试视图是否调度了正确的操作。
如果您经常这样做,您还可以使用优秀的Sinon存根/模拟库,它可以让您轻松创建spy个功能:
let dispatch = sinon.spy();
let subject = shallow(<Layout movies={movies} dispatch={dispatch} />);
expect(dispatch.calledWith(expectedAction)).to.be.true;