[英]Testing debounced function in React component with Jest and Enzyme
[英]React testing state of component with Jest and Enzyme
我有一个简单的组件,您单击一个按钮,它使用提取来调用API并记录结果:
class App extends Component {
constructor(props) {
super(props);
this.state = {isLoading: false};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({isLoading: true});
return fetch('https://api.github.com/users/londonappdev')
.then(res => {
return res.json();
})
.then(data => {
console.log(data);
this.setState({isLoading: false})
});
}
render() {
return (
<div className="App">
<button onClick={this.handleClick}>Click</button>
</div>
);
}
}
我正在尝试测试isLoading
在请求进行时设置为true
,然后在请求完成后设置为false
。
我的测试看起来像这样:
it('sets isloading to true while loading', () => {
global.fetch = jest.fn().mockReturnValue(Promise.resolve({
ok: true,
json: () => Promise.resolve({'user': 'test'})
}));
const c = shallow(<App />);
c.instance().handleClick().then(() => {
expect(c.instance().state.isLoading).toEqual(false);
});
expect(c.instance().state.isLoading).toEqual(true);
});
这是有效的,但我的问题是:以这种方式测试状态是否安全/可靠? 由于setState
是异步的,因此可能是expect(c.instance().state.isLoading).toEqual(true);
在状态正确设定之前会被调用吗?
有关测试此类组件的最佳方法的任何建议将非常感激。
是的,这是非常安全的。 与setTimeout(callback, 0)
类似,promise回调排队等待在其余同步代码之后运行。 这可以确保您的断言将在程序中的正确位置运行。
单元测试的小技巧 - 而不是调用c.instance().handleClick()
我会调用c.find('button').prop('onClick')()
。 您的组件是您正在测试的“单元”,因此您应该尽量避免访问内部方法/属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.