Skip to content
This repository has been archived by the owner on Feb 7, 2023. It is now read-only.

ReferenceError: Request is not defined #65

Closed
Stono opened this issue Oct 24, 2020 · 5 comments
Closed

ReferenceError: Request is not defined #65

Stono opened this issue Oct 24, 2020 · 5 comments

Comments

@Stono
Copy link

Stono commented Oct 24, 2020

Having the strangest behaviour that I can't get to the bottom of since trying v2.0.0 of this module.

Given this really simple module, worker.ts:

export default async function handleRequest(
  request: Request
): Promise<Response> {
  const newRequest = new Request(request)
  const defaultScore = 99
  newRequest.headers.set(
    'Cf-Bot-Score',
    (request.cf.botManagement?.score || defaultScore).toString()
  )
  return fetch(newRequest)
}

And this really simple mocha test: worker.test.ts:

import handleRequest from 'lib/worker'
describe('Worker', () => {
  it('should map the bot score to a request header', async () => {
    const request = {
      cf: {
        botManagement: {
          score: 50
        }
      }
    } as Request
    const result = await handleRequest(request)
    console.log(result)
  })
})

And the following tsconfig:

{
  "compilerOptions": {
    "types": ["@cloudflare/workers-types", "mocha"],
    "module": "CommonJS",
    "target": "es2020",
    "lib": ["es2017", "WebWorker"],
    "rootDir": "./",
    "outDir": "./built",
    "baseUrl": "./",
    "allowJs": true,
    "checkJs": true,
    "alwaysStrict": true,
    "noImplicitAny": false,
    "noImplicitThis": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "noEmitOnError": false,
    "sourceMap": false
  },
  "include": ["lib/**/*.ts", "test/**/*.ts"],
  "exclude": ["node_modules"]
}

In the GUI (vscode) all intellisense is working fine, and typescript compiles fine too.

However, when running the tests via Mocha, I get:

❯ ./node_modules/.bin/mocha -r ts-node/register -r tsconfig-paths/register test/index.test.ts 
  Worker
    1) should map the bot score to a request header

  0 passing (9ms)
  1 failing

  1) Worker
       should map the bot score to a request header:
     ReferenceError: Request is not defined
      at Object.handleRequest [as default] (lib/worker.ts:4:22)
      at Context.<anonymous> (test/index.test.ts:11:39)
      at processImmediate (internal/timers.js:458:21)

So specifically on the line:

const newRequest = new Request(request)

Therefore it seems fine with the interface use in the function parameters:

export default async function handleRequest(
  request: Request
): Promise<Response> {

Any ideas?

@Stono
Copy link
Author

Stono commented Oct 24, 2020

Hmm looks like this might be a ts-node problem rather than worker-types TypeStrong/ts-node#711, and I've created TypeStrong/ts-node#1134 to see if anyone has any ideas there.

@xtuc
Copy link
Member

xtuc commented Nov 24, 2020

If you are running the worker in Node. The Request Object doesn't exists. You can polyfill it using https://github.com/node-fetch/node-fetch#class-request locally to fix that issue.

@armfazh
Copy link

armfazh commented Jul 2, 2021

Here it is a solution that worked for me, but I'm using jest.

Include node-fetch in your devDependencies

devDependencies{
+        "node-fetch": "^2.6.1",
}

Add these lines to a mocha setup Javascript file (not TS), or just before your tests.

+ import nodeFetch from 'node-fetch'
+ // Mocking fetch Web API using node-fetch
+ if (typeof fetch === 'undefined') {
+   global.fetch = nodeFetch
+   global.Request = nodeFetch.Request
+ }

you might be tempted to add @types/node-fetch, I tried without success.

@threepointone
Copy link
Contributor

The above fix seems about right. But this only patches one global, and you'll have to do the rest of the environment as well. A proper (supported) option is to use miniflare, which is a full simulation of the Workers environment https://miniflare.dev/. Closing this issue.

@waldemarennsaed
Copy link

Update 2022:

The above fix worked for me as well.

Please note: Using TS will throw TS errors for not-overlapping types.
Make sure to use a plain setup.js file.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants