Skip to content

Commit

Permalink
fix test
Browse files Browse the repository at this point in the history
  • Loading branch information
jshawl committed Mar 19, 2024
1 parent 75223e2 commit 2a9cc21
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 71 deletions.
42 changes: 32 additions & 10 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,37 @@
/**
* Welcome to Cloudflare Workers! This is your first worker.
*
* - Run `npm run dev` in your terminal to start a development server
* - Open a browser tab at http://localhost:8787/ to see your worker in action
* - Run `npm run deploy` to publish your worker
*
* Learn more at https://developers.cloudflare.com/workers/
*/
const validate = async (request) => {
const required = ['subject', 'to'];
let data;
try {
data = (await request.json()) ?? {};
} catch (e) {
data = {};
}

data.errors = required.reduce((acc, el) => {
if (!data[el]) {
return [...acc, `missing required parameter '${el}'`];
}
return acc;
}, []);

return data;
};

export default {
async fetch(request, env, ctx) {
return new Response('Hello World!!');
const { pathname } = new URL(request.url);
if (pathname === '/api/notify') {
const { subject, to, errors } = await validate(request);
const body = {
subject,
to,
};
const response = {
...body,
...(errors.length && { errors }),
};
return new Response(JSON.stringify(response), { status: errors.length ? 400 : 200 });
}
return new Response(null, { status: 404 });
},
};
41 changes: 28 additions & 13 deletions test/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,37 @@ import { env, createExecutionContext, waitOnExecutionContext, SELF } from 'cloud
import { describe, it, expect } from 'vitest';
import worker from '../src';

describe('Hello World worker', () => {
it('responds with Hello World! (unit style)', async () => {
const request = new Request('http://example.com');
// Create an empty context to pass to `worker.fetch()`.
describe('API', () => {
it('errors for missing required parameters', async () => {
const request = new Request('http://example.com/api/notify', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
});
const ctx = createExecutionContext();
const response = await worker.fetch(request, env, ctx);
// Wait for all `Promise`s passed to `ctx.waitUntil()` to settle before running test assertions
await waitOnExecutionContext(ctx);
expect(await response.text()).toMatchInlineSnapshot(`"Hello World!!"`);
expect(await response.json()).toEqual({
errors: ["missing required parameter 'subject'", "missing required parameter 'to'"],
});
expect(response.status).toEqual(400);
});

it('responds with Hello World! (integration style)', async () => {
const request = new Request('http://example.com');
const env = {};
const ctx = {};
const response = await SELF.fetch(request, env, ctx);
expect(await response.text()).toMatchInlineSnapshot(`"Hello World!!"`);
it('does not error if the required parameters are present', async () => {
const request = new Request('http://example.com/api/notify', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
to: '[email protected]',
subject: 'hello world',
}),
});
const ctx = createExecutionContext();
const response = await worker.fetch(request, env, ctx);
await waitOnExecutionContext(ctx);
expect(await response.json()).toEqual(expect.not.objectContaining({ errors: [] }));
expect(response.status).toEqual(200);
});
});
48 changes: 0 additions & 48 deletions wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,51 +2,3 @@ name = "api"
main = "src/index.js"
compatibility_date = "2024-03-14"
compatibility_flags = ["nodejs_compat"]

# Variable bindings. These are arbitrary, plaintext strings (similar to environment variables)
# Note: Use secrets to store sensitive data.
# Docs: https://developers.cloudflare.com/workers/platform/environment-variables
# [vars]
# MY_VARIABLE = "production_value"

# Bind a KV Namespace. Use KV as persistent storage for small key-value pairs.
# Docs: https://developers.cloudflare.com/workers/runtime-apis/kv
# [[kv_namespaces]]
# binding = "MY_KV_NAMESPACE"
# id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

# Bind an R2 Bucket. Use R2 to store arbitrarily large blobs of data, such as files.
# Docs: https://developers.cloudflare.com/r2/api/workers/workers-api-usage/
# [[r2_buckets]]
# binding = "MY_BUCKET"
# bucket_name = "my-bucket"

# Bind a Queue producer. Use this binding to schedule an arbitrary task that may be processed later by a Queue consumer.
# Docs: https://developers.cloudflare.com/queues/get-started
# [[queues.producers]]
# binding = "MY_QUEUE"
# queue = "my-queue"

# Bind a Queue consumer. Queue Consumers can retrieve tasks scheduled by Producers to act on them.
# Docs: https://developers.cloudflare.com/queues/get-started
# [[queues.consumers]]
# queue = "my-queue"

# Bind another Worker service. Use this binding to call another Worker without network overhead.
# Docs: https://developers.cloudflare.com/workers/platform/services
# [[services]]
# binding = "MY_SERVICE"
# service = "my-service"

# Bind a Durable Object. Durable objects are a scale-to-zero compute primitive based on the actor model.
# Durable Objects can live for as long as needed. Use these when you need a long-running "server", such as in realtime apps.
# Docs: https://developers.cloudflare.com/workers/runtime-apis/durable-objects
# [[durable_objects.bindings]]
# name = "MY_DURABLE_OBJECT"
# class_name = "MyDurableObject"

# Durable Object migrations.
# Docs: https://developers.cloudflare.com/workers/learning/using-durable-objects#configure-durable-object-classes-with-migrations
# [[migrations]]
# tag = "v1"
# new_classes = ["MyDurableObject"]

0 comments on commit 2a9cc21

Please sign in to comment.