diff --git a/src/utils/after1000ms.ts b/src/utils/after1000ms.ts new file mode 100644 index 0000000..53e8c5f --- /dev/null +++ b/src/utils/after1000ms.ts @@ -0,0 +1,11 @@ +type AnyFunction = (...args: any[]) => any; + +const after1000ms = (callback: AnyFunction) => { + console.log("准备计时"); + setTimeout(() => { + console.log("午时已到"); + callback && callback(); + }, 1000); +}; + +export default after1000ms; diff --git a/tests/jest-setup.ts b/tests/jest-setup.ts index 801bd48..752b680 100644 --- a/tests/jest-setup.ts +++ b/tests/jest-setup.ts @@ -13,3 +13,8 @@ afterEach(() => { afterAll(() => { server.close(); }); + +// Mock console.xxx +jest.spyOn(console, "log").mockImplementation(); +jest.spyOn(console, "warn").mockImplementation(); +jest.spyOn(console, "error").mockImplementation(); diff --git a/tests/utils/after1000ms.test.ts b/tests/utils/after1000ms.test.ts new file mode 100644 index 0000000..90fa27d --- /dev/null +++ b/tests/utils/after1000ms.test.ts @@ -0,0 +1,20 @@ +import after1000ms from "utils/after1000ms"; + +describe("after1000ms", () => { + beforeAll(() => { + jest.useFakeTimers(); + }); + + it("可以在 1000ms 后自动执行函数", () => { + jest.spyOn(global, "setTimeout"); + const callback = jest.fn(); + + after1000ms(callback); + + jest.runAllTimers(); + + expect(callback).toHaveBeenCalled(); + expect(setTimeout).toHaveBeenCalledTimes(1); + expect(setTimeout).toHaveBeenCalledWith(expect.any(Function), 1000); + }); +});