question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

ReferenceError: Request is not defined

See original GitHub issue

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?

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:1
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

3reactions
armfazhcommented, 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.

0reactions
waldemarennsaedcommented, Jan 6, 2022

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.

Read more comments on GitHub >

github_iconTop Results From Across the Web

ReferenceError: request is not defined - node.js - Stack Overflow
You have not installed request module. First install it npm install --save request and then include it var request = require('request');.
Read more >
ReferenceError: request is not defined (Example) - Treehouse
Has anyone encountered the error 'ReferenceError: request is not defined' when trying to follow the get method example?
Read more >
ReferenceError: request is not defined - jsreport forum
This means that there is a non-existent variable referenced somewhere. This variable needs to be declared, or you need to make sure it...
Read more >
Referenceerror request is not defined node js - Weebly
my requirement is to send parallel call-out from APIGEE to multiple objects (Accounts, Contacts etc.,) in Salesforce. I am trying to do this...
Read more >
Vue-test-utils, jest; ReferenceError: Request is not defined
ReferenceError : Request is not defined. Here's the code snippet of my test case: it('Expect login to pass validation on submit', ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found