当我点击这里的按钮时,我正在尝试专注于div .我把我的问题减少到下面的代码,虽然在div对象上调用焦点,但从不调用onFocus.也autoFocus没有解决我的问题,因为我希望能够在组件安装后多次更改焦点.
class App extends React.Component {
constructor() {
super();
this.my_refs = {};
this.focusByID.bind(this);
}
focusByID(id){
let myRef = this.my_refs[id];
if(myRef){
console.log('focusing on ', id, myRef);
myRef.focus();
}
}
render() {
return (
<div>
<div
id="bigRedDiv"
style={{height : 200, width : 200, backgroundColor : 'red'}}
ref={(input) => this.my_refs['bigRedDiv'] = input }
onFocus={() => console.log('FOCUS IS ON BIG RED DIV')}
onClick={() => this.focusByID('bigRedDiv')}
>
</div>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个包含此代码的小提琴.
我有这个React组件
export class Timer extends Component {
constructor(props) {
super(props);
this.state = {i : props.i};
}
componentDidMount(){
this.decrementCounter();
}
decrementCounter(){
if(this.state.i < 1){
return;
}
setTimeout(() => {
this.setState({i : this.state.i - 1})
this.decrementCounter()}, 1000);
}
render(){
return <span>{this.state.i}</span>
}}
Run Code Online (Sandbox Code Playgroud)
我想表达一个这样的测试
jest.useFakeTimers();
it('should decrement timer ', () => {
const wrapper = shallow(<Timer i={10} />);
expect(wrapper.text()).toBe("10");
jest.runOnlyPendingTimers();
expect(wrapper.text()).toBe("9");
});
Run Code Online (Sandbox Code Playgroud)
目前是第一次预期通过,但第二次失败
Expected value to be (using ===):
"9"
Received:
"10"
Run Code Online (Sandbox Code Playgroud)
我该如何正确测试这个组件?
如本箱所示,为预览按钮指定的宽度为 120 px,而渲染宽度始终为 132 px(在不同屏幕上)。
.btn-grey{
cursor: pointer;
background: #f1f3f6;
border: 1px solid #d7d9e1;
box-shadow: 1px 1px 1px #fff inset;
border-radius: 3px;
color: #838AAB;
display: inline-block;
height: 30px;
padding: 0 5px;
}Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div style="display: flex; width: 60%; justify-content: center;">
<input name="preview" class="btn-grey" value="Preview" style="flex-basis: 120px; width: 120px; height: 35px;max-width: 120px; max-height: 35px; margin : 5px 5px 5px 5px " title="preview"/>
<input name="load" class="btn-grey" type="submit" value="Load …Run Code Online (Sandbox Code Playgroud)