[英]How can I check that a jQuery chainable functions was called in unit test
[英]How I can unit test if log is called
我有這樣的組件。 它是另一個組件的包裝組件。 有onClick函數,如果是鼠標事件,應調用日志
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);
}
我需要測試它是否叫做this.props.log。 我有一個單元測試,但它不起作用。 我如何使用jest,酶來做到這一點?
it("should not log if has not mouse event", () => {
const onClickMock = jest.fn();
const logMock = jest.fn();
const ButtonWithLog = withPressedLog(Button, {
type: "BUTTON_PRESSED",
});
const subject = mountProvider(ButtonWithLog, { onClick: onClickMock, log: logMock });
const mockedEvent = { target:{} };
subject.find(ButtonWithLog).simulate("click", mockedEvent);
expect(onClickMock.mock.calls).toHaveLength(1);
expect(logMock.mock.calls).toHaveLength(0); // not works correctly, always return []
});
商店
const store = createStore(() => ({}));
const dispatchMock = jest.fn();
store.dispatch = dispatchMock;
mountProvider函數
function mountProvider(
Component,
props,
) {
return mount(
<Provider store={store}>
<Component {...props} />
</Provider>,
);
}
我認為這里的問題是你實際上在測試連接的組件,而不是未包裝的組件。
嘗試隔離您正在測試的組件。 例如,您可以在連接的組件上使用酶的淺包裝和dive
方法,直接進入未包裝的組件。
具體來說,您的問題可能是您的連接組件從商店獲取log
道具(通過mapDispatchToProps
),但商店被mapDispatchToProps
,因此它不起作用。 在測試中,您將一些模擬函數作為prop傳遞給組件,但是一旦組件連接,引用就會丟失。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.