workers-sdk icon indicating copy to clipboard operation
workers-sdk copied to clipboard

🚀 Feature Request: wrangler init should also generate an example test

Open rozenmd opened this issue 3 years ago • 4 comments

Describe the solution

Just a test that index.ts/index.js returns "Hello World!" as expected

This should probably be an option as part of the init flow, you actually have to do a bunch of stuff to get Jest working:

For TypeScript

npm i -D jest babel-jest @babel/core @babel/preset-env @babel/preset-typescript @types/jest
  • add "test": "jest" to package.json scripts
  • create a babel.config.js (if babel.config.js already exists, let the user know to add "@babel/preset-typescript" to the presets array):
//babel.config.js
module.exports = {
  presets: [
    ["@babel/preset-env", { targets: { node: "current" } }],
    "@babel/preset-typescript",
  ],
};
  • add @types/jest to the types array in tsconfig.json

  • add an index.test.ts:

//index.test.ts
import { unstable_dev } from 'wrangler'

describe("worker", () => {
	it("should return Hello World", async () => {
		const worker = await unstable_dev(
			"src/index.ts",
			{},
			{ disableExperimentalWarning: true }
		);
		const resp = await worker.fetch();
		if (resp) {
			const text = await resp.text();
			expect(text).toMatchInlineSnapshot(`"Hello World!"`);
		}
		await worker.stop();
	});
});

Additional test runners to implement:

  • Ava
  • Mocha
  • vitest

rozenmd avatar Sep 05 '22 11:09 rozenmd

This is a great idea. I love that it actually tests the initial behaviour, which will break once people start changing the Worker. We have discussed if Jest is the runner we want to use; probably we might offer a selection?

petebacondarwin avatar Sep 05 '22 15:09 petebacondarwin

+1 To offering choices between multiple tests suites, would be nice to at least include Ava & Mocha.

Skye-31 avatar Sep 05 '22 15:09 Skye-31

Un-assigning myself as I've got plenty of stuff to focus on - feel free to ask questions if you want to pick this up!

rozenmd avatar Sep 06 '22 15:09 rozenmd

Ooooh Vitest! I like that idea 😄

JacobMGEvans avatar Sep 06 '22 19:09 JacobMGEvans

+1 To offering choices between multiple tests suites, would be nice to at least include Ava & Mocha.

@Skye-31 Could consider those, since they are also major commonly used runners/suites

JacobMGEvans avatar Dec 29 '22 16:12 JacobMGEvans

We'll address this as part of the upcoming work on Miniflare's unit testing environment cc @admah @mrbbot

penalosa avatar Nov 15 '23 15:11 penalosa

The "Hello World" Worker templates (JS and TS) generated via C3 now include @cloudflare/vitest-pool-workers and an example test.

Closed by #5189

admah avatar Apr 02 '24 21:04 admah