workerd icon indicating copy to clipboard operation
workerd copied to clipboard

BUG: Type Mismatch Between DurableObject Abstract Class and DurableObject Interface for fetch Method

Open HiraiKyo opened this issue 9 months ago • 2 comments

Abstract

I recently encountered a type mismatch issue while writing test code for Cloudflare Worker's DurableObject by @cloudflare/vitest-pool-worker. The problem arises due to the fetch method being undefined, following the example provided in honojs/examples for creating a DurableObject.

Packages

  • "@cloudflare/vitest-pool-workers": "0.2.6",
  • "@cloudflare/workers-types": "4.20240502.0",
  • "@faker-js/faker": "~8.4.1",
  • "vitest": "1.3.0",
  • "wrangler": "3.53.1"

Codes

src/Matchmaking.ts

export class MatchmakingDurableObject extends DurableObject {
  async addQueue(firebaseUser: FirebaseUser): Promise<void>{
   // ...
  }

  async removeQueue(firebaseUser: FirebaseUser): Promise<void>{
  // ...  
  }
}

test/Matchmaking.spec.ts

describe("MatchmakingDurableObject", () => {
  it("Successful addQueue", async () => {
    const id = env.MATCHMAKING.idFromName("matchmaking");
    const stub = env.MATCHMAKING.get(id);
    await runInDurableObject<MatchmakingDurableObject, DurableObjectState>(stub, async (instance, state) => {
      instance.addQueue(MockFirebaseUsers[0]);
      const stored = await state.storage.get("queue");
      expect(stored).toBeTypeOf("string");
      const queue = JSON.parse(stored as string)
      expect(queue.length).toBe(1);
    })
  });
});

tsconfig.json

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "strict": true,
    "skipLibCheck": true,
    "lib": [
      "ESNext"
    ],
    "types": [
        "@cloudflare/workers-types/experimental",
    ],
    "jsx": "react-jsx",
    "jsxImportSource": "hono/jsx"
  },
}

test/tsconfig.json

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "moduleResolution": "bundler",
    "types": [
      "@cloudflare/workers-types/experimental",
      "@cloudflare/vitest-pool-workers"
    ]
  },
  "include": ["./**/*.ts", "../src/env.d.ts"]
}

Error log on vscode

Type 'MatchmakingDurableObject' does not satisfy the constraint 'DurableObject'.
  Types of property 'fetch' are incompatible.
    Type '((request: Request<unknown, CfProperties<unknown>>) => Response | Promise<Response>) | undefined' is not assignable to type '(request: Request<unknown, CfProperties<unknown>>) => Response | Promise<Response>'.
      Type 'undefined' is not assignable to type '(request: Request<unknown, CfProperties<unknown>>) => Response | Promise<Response>'.ts(2344)

Notes

This commit of the example is just 1 week ago, so I know this is the new error. https://github.com/honojs/examples/commit/9b7acf119e874f389ca386fb2406c8f2110039e6 Temporarily I just define the fetch method on the DurableObject for the test, strangely.

HiraiKyo avatar May 09 '24 09:05 HiraiKyo