worker-typescript-template icon indicating copy to clipboard operation
worker-typescript-template copied to clipboard

There is some problem with testing code

Open Iezuni opened this issue 3 years ago • 3 comments

When I use fetch('someUrl') in my code, the jest will report a bug like ReferenceError: fetch is not defined. How can I solve this problem?

Iezuni avatar Jun 15 '21 13:06 Iezuni

Local tests run in node. Node does not implement the fetch api.

There are a number of packages for mocking the fetch api, jest-fetch-mock has typescipt definitions https://www.npmjs.com/package/jest-fetch-mock#to-setup-for-an-individual-test

Here's an example basic usage https://github.com/cloudflare/worker-typescript-template/tree/example-jest-fetch-mock

koeninger avatar Jun 15 '21 17:06 koeninger

Miniflare is a good replacement for the existing mock. It actually simulates fetch properly.

Example (haven't extracted it back for the PR yet): https://github.com/nelsonjchen/gtr-proxy/tree/snapshot-miniflare-replacement

nelsonjchen avatar Mar 06 '22 06:03 nelsonjchen

https://github.com/cloudflare/worker-typescript-template/pull/58

Oh someone beat me to it by 5 days.

nelsonjchen avatar Mar 06 '22 06:03 nelsonjchen