Search code examples
testingcloudflare-workers

how should I test the http response from a Cloudflare service using wrangler v3?


I have a Cloudflare service and would like to test its http responses. Best I can tell, I should be using wrangler v3's local workerd runtime. There is a sample but it is quite minimal so I have a few sub-questions:

Q1: Do I, somehow, run the service in one workerd nanoservice and run tests in other nanoservices? If so, how do I launch the service from the config.capnp?

Q2: The top of the config.capnp in the unit-tests sample suggests that it may be auto-generated at some point. Is this currently possible or advisable?

Q3: Should I use a service binding to send a fetch request from a test nanoservice to the service it is testing?

Q4: There is mention at https://blog.cloudflare.com/wrangler3/ that vitest integration is progressing. Is there an example of a test which exercises/exorcises a service?

Testing at this level is quite common and test-driven development places a focus on pre-emptive tests so I anticipate that examples and documentation are available. Regrettably, my search found a lot of information on Miniflare v2 but not for the latest Wrangler release and the workerd runtime.


Solution

  • Wrangler exposes an unstable_dev() API which lets you programmatically spin-up Workers and send fetch requests to them, so you can assert the responses are as you expect with your preference of testing framework such as Vitest.

    https://developers.cloudflare.com/workers/wrangler/api/

    For the available options you can pass to unstable_dev(), refer to UnstableDevOptions.

    The Vitest integration you are referring to is the Miniflare environment, where you can access the KV/R2/etc bindings to assert that your Worker is interacting with those properly. That isn't back in Wrangler 3 at the time of writing, but is on the roadmap and will hopefully land in the coming months.