test: try mock Date.now to reduce test time

This commit is contained in:
shaodahong 2019-08-08 20:32:06 +08:00 committed by shao
parent b277a963f0
commit 83022a4cff

View File

@ -1,15 +1,38 @@
import scrollTo from '../scrollTo';
import { sleep } from '../../../tests/utils';
describe('Test ScrollTo function', () => {
let dateNowMock;
beforeAll(() => {
jest.useFakeTimers();
});
afterAll(() => {
jest.useRealTimers();
});
beforeEach(() => {
dateNowMock = jest
.spyOn(Date, 'now')
.mockImplementationOnce(() => 0)
.mockImplementationOnce(() => 1000);
});
afterEach(() => {
dateNowMock.mockRestore();
});
it('test scrollTo', async () => {
const scrollToSpy = jest.spyOn(window, 'scrollTo').mockImplementation((x, y) => {
window.scrollY = y;
window.pageYOffset = y;
});
scrollTo(1000);
await sleep(500);
jest.runAllTimers();
expect(window.pageYOffset).toBe(1000);
scrollToSpy.mockRestore();
});
@ -18,7 +41,7 @@ describe('Test ScrollTo function', () => {
scrollTo(1000, {
callback: cbMock,
});
await sleep(500);
jest.runAllTimers();
expect(cbMock).toHaveBeenCalledTimes(1);
});
@ -27,7 +50,7 @@ describe('Test ScrollTo function', () => {
scrollTo(1000, {
getContainer: () => div,
});
await sleep(500);
jest.runAllTimers();
expect(div.scrollTop).toBe(1000);
});
});