Prechádzať zdrojové kódy

test: re-create mocks for drizzle, fs-extra and redis using vi.mock

Nicolas Meienberger 2 rokov pred
rodič
commit
9feec710bc
4 zmenil súbory, kde vykonal 75 pridanie a 0 odobranie
  1. 7 0
      tests/mocks/drizzle.ts
  2. 33 0
      tests/mocks/fs-extra.ts
  3. 32 0
      tests/mocks/redis.ts
  4. 3 0
      tsconfig.json

+ 7 - 0
tests/mocks/drizzle.ts

@@ -0,0 +1,7 @@
+import { vi } from 'vitest';
+
+export const mockSelect = <T>(returnValue: T) => vi.fn(() => ({ from: vi.fn(() => ({ where: vi.fn(() => returnValue) })) }));
+
+export const mockInsert = <T>(returnValue: T) => vi.fn(() => ({ values: vi.fn(() => ({ returning: vi.fn(() => returnValue) })) }));
+
+export const mockQuery = <T>(returnValue: T) => ({ userTable: { findFirst: vi.fn(() => returnValue) } });

+ 33 - 0
tests/mocks/fs-extra.ts

@@ -0,0 +1,33 @@
+import path from 'path';
+
+let mockFiles = Object.create(null);
+export const fsExtraMock = {
+  default: {
+    __createMockFiles: (newMockFiles: Record<string, string>) => {
+      mockFiles = Object.create(null);
+
+      // Create folder tree
+      Object.keys(newMockFiles).forEach((file) => {
+        const dir = path.dirname(file);
+
+        if (!mockFiles[dir]) {
+          mockFiles[dir] = [];
+        }
+
+        mockFiles[dir].push(path.basename(file));
+        mockFiles[file] = newMockFiles[file];
+      });
+    },
+    existsSync: (p: string) => mockFiles[p] !== undefined,
+    promises: {
+      unlink: async (p: string) => {
+        if (mockFiles[p] instanceof Array) {
+          mockFiles[p].forEach((file: string) => {
+            delete mockFiles[path.join(p, file)];
+          });
+        }
+        delete mockFiles[p];
+      },
+    },
+  },
+};

+ 32 - 0
tests/mocks/redis.ts

@@ -0,0 +1,32 @@
+import { vi } from 'vitest';
+
+export const redisMock = {
+  createClient: vi.fn(() => {
+    const values = new Map();
+    const expirations = new Map();
+    return {
+      isOpen: true,
+      connect: vi.fn(),
+      set: (key: string, value: string, exp: number) => {
+        values.set(key, value);
+        expirations.set(key, exp);
+      },
+      get: (key: string) => values.get(key),
+      quit: vi.fn(),
+      del: (key: string) => values.delete(key),
+      ttl: (key: string) => expirations.get(key),
+      on: vi.fn(),
+      keys: (key: string) => {
+        const keyprefix = key.substring(0, key.length - 1);
+        const keys = [];
+        // eslint-disable-next-line no-restricted-syntax
+        for (const [k] of values) {
+          if (k.startsWith(keyprefix)) {
+            keys.push(k);
+          }
+        }
+        return keys;
+      },
+    };
+  }),
+};

+ 3 - 0
tsconfig.json

@@ -18,6 +18,9 @@
       "@/shared/*": [
       "@/shared/*": [
         "./src/shared/*"
         "./src/shared/*"
       ],
       ],
+      "@/tests/*": [
+        "./tests/*"
+      ],
     },
     },
     "lib": [
     "lib": [
       "dom",
       "dom",