Skip to content
代码片段 群组 项目
提交 c2c87592 编辑于 作者: Marina Mosti's avatar Marina Mosti
浏览文件

Docs: testing cleanup timers listeners

上级 a49a320f
No related branches found
No related tags found
无相关合并请求
...@@ -435,6 +435,49 @@ it('passes', () => { ...@@ -435,6 +435,49 @@ it('passes', () => {
}); });
``` ```
### Testing clean-up of event listeners and timeouts
Often times in components we create event listeners or timeouts on the `beforeDestroy` (`beforeUnmount` for Vue 3) hooks. It is important to test that both listeners and timeouts are cleared when the component instance is destroyed, as forgetting to clean up these events can cause problems like memory leaks and broken references on event listeners.
Consider the following example:
```javascript
beforeDestroy() {
removeEventListener('keydown', someListener)
clearTimeout(timeoutPointer)
}
```
In the above example, a component is both clearing a `keydown` event listener and a timeout that was created elsewhere.
Let's take a look at the relevant tests.
```javascript
describe('Cleanup before destroy', () => {
beforeEach(() => {
createComponent()
// Destroy the component immediately to invoke the `beforeDestroy` hook
wrapper.destroy()
})
it('removes the event listener', () => {
const spy = jest.spyOn(window, 'removeEventListener')
expect(spy).toHaveBeenCalledTimes(1)
expect(spy).toHaveBeenCalledWith('keydown', expect.any(Function))
})
it('clears the pending timeouts', () => {
const spy = jest.spyOn(window, 'clearTimeout')
expect(spy).toHaveBeenCalledTimes(1)
})
})
```
The above example does not explicitly check for the function that is called on the `keydown` listener as it will normally be an implementation detail. The same happens with the `clearTimeout` call, as the parameter will be a pointer to a timer created internally in the component.
Due to this, it is normally sufficient to check that the spies have been called, with the recommended addition of checking the _times_ that they have been called.
### Waiting in tests ### Waiting in tests
Sometimes a test needs to wait for something to happen in the application before it continues. Sometimes a test needs to wait for something to happen in the application before it continues.
......
0% 加载中 .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册