所以我遇到了一个小问题,我被难住了......
如果满足特定条件,我有一个Link组件将通过道具进入特定路线。to如果不满足该条件,则单击该链接将执行其他操作(在我的情况下启动自定义模式)。
我有一个绑定到onClick我Link组件上的处理程序的类方法
// Card.jsx
import Link from 'components/Link';
...
static props = {
condition: PropTypes.bool
};
constructor(props) {
this.state = {
showModal: false
};
}
...
goToUrlOrLaunchModal() {
return (
<Link
to="www.google.com"
onClick={this.handleClick}
/>
);
}
...
handleClick(e) {
const { condition } = this.props;
if (!condition) {
e.preventDefault();
this.setState({
showModal: true
});
}
}
我的问题是单元测试。我有一个单元测试,用于在何时单击condition链接false
// Card.test.js
...
import renderer from 'react-test-renderer';
...
const event = {
preventDefault: jest.fn()
};
const component = renderer.create(<Card>).getInstance();
instance.handleClick(event);
expect(event.preventDefault).toHaveBeenCalled();
expect(instance.state.showModal).toBe(true);
我迷路的地方是测试另一方 - 什么时候condition,true之后我不需要调用preventDefault或执行任何逻辑。我不需要任何东西handleClick来开火。唯一的逻辑handleClick是何时condition为假。
单击组件时去路由的逻辑Link很好,它只是 when conditionis的单元测试true。
我需要测试preventDefault没有被调用的,那instance.state.showModal是true,但我很难过。这是我一直认为它必须的,但无法超越它......
const event = {
preventDefault: jest.fn()
};
expect(instance.handleManageClick).not.toHaveBeenCalled();
expect(event.preventDefault).not.toHaveBeenCalled();
expect(instance.state.showModal).toBe(false);
如果有人有一些指导,将不胜感激!谢谢!