Skip to content

Commit

Permalink
feat: 添加 after1000ms 以及测试,并 Mock console 的 API
Browse files Browse the repository at this point in the history
  • Loading branch information
haixiangyan authored and haixiangyan committed Apr 28, 2022
1 parent 316025d commit 5fdd793
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
11 changes: 11 additions & 0 deletions 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;
5 changes: 5 additions & 0 deletions tests/jest-setup.ts
Expand Up @@ -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();
20 changes: 20 additions & 0 deletions 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);
});
});

0 comments on commit 5fdd793

Please sign in to comment.