Javascript 如果调用了log,如何进行单元测试
我有这样的成分。它是另一个组件的包装器组件。有onClick函数,如果是鼠标事件,它应该调用日志Javascript 如果调用了log,如何进行单元测试,javascript,reactjs,frontend,jestjs,enzyme,Javascript,Reactjs,Frontend,Jestjs,Enzyme,我有这样的成分。它是另一个组件的包装器组件。有onClick函数,如果是鼠标事件,它应该调用日志 import log from './log'; export function withPressedLog( Component, options, ) { class WithPressedLogComponent extends React.Component { constructor(props) { super(prop
import log from './log';
export function withPressedLog(
Component,
options,
) {
class WithPressedLogComponent extends React.Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
}
public render() {
const { ...props } = this.props;
return <Component {...props} onClick={this.onClick} />;
}
private onClick(e) {
if (this.props.onClick !== undefined) {
this.props.onClick(e);
}
if (e) {
this.props.log();
}
}
}
const mapDispatchToProps = {
log: () => log(options),
};
return connect(
undefined,
mapDispatchToProps,
)(WithPressedLogComponent);
}
贮藏
挂载提供程序函数
function mountProvider(
Component,
props,
) {
return mount(
<Provider store={store}>
<Component {...props} />
</Provider>,
);
}
函数安装提供程序(
组成部分,
道具,
) {
回座(
,
);
}
我认为这里的问题在于,您实际上是在测试连接的组件,而不是未包装的组件
尝试隔离您正在测试的组件。例如,您可以对连接的组件使用Ezyme的浅包装器和dive
方法,直接到达未包装的组件
具体来说,您的问题可能是您连接的组件正在从存储中获取日志
道具(通过mapDispatchToProps
),但存储被模拟,因此无法工作。在测试中,您将一些模拟函数作为道具传递给组件,但是一旦组件连接,引用就会丢失
您的
mountPovider
来自哪里?Hinrich我将此函数添加到代码中
const store = createStore(() => ({}));
const dispatchMock = jest.fn();
store.dispatch = dispatchMock;
function mountProvider(
Component,
props,
) {
return mount(
<Provider store={store}>
<Component {...props} />
</Provider>,
);
}