# 处理异步测试
# 处理异步计时器
对于定时器, vi (opens new window) 工具中提供了对应的 api ,来模拟计时器。
- vi.useFakeTimers
启用模拟计时器,使用当前 api 后就可以使用其他 api 模拟计时器的使用。
关联 api:
- vi.useRealTimers、runAllTimers等。
import { describe, it, expect, test, vi } from 'vitest';
export class User {
id: string;
constructor(id: string) {
this.id = id;
}
fetchData(callback: (data: string) => void, delay: number): void {
setTimeout(() => {
const data = `Data for user with id: ${this.id}`;
callback(data);
}, delay);
}
}
describe('setTimeout', () => {
it('should fetch User data', () => {
vi.useFakeTimers();
const user = new User('1');
const callback = vi.fn();
user.fetchData(callback, 100);
vi.runAllTimers();
expect(callback).toHaveBeenCalledWith('Data for user with id: 1');
});
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27