Hands-on guide to Vitest

Hands-on guide to Vitest

Hi, this is Charu from Classmethod.

Vitest is a fast testing framework built for modern JavaScript applications, designed to work seamlessly with Vite. In this blog, we'll focus on installing and setting up Vitest in a project, writing tests, and running them to ensure everything works as expected.

Let's get started!

To proceed with the testing, I will show you the program which we are testing.

In this blog, we will be using pnpm for our installation.

Installing vitest

Use the following command to install vitest,

pnpm add -D vitest

Adding a Sample Component

To test vitest, I created a simple lambda handler function as lambda/src/todoFunc/index.ts,

export const handler = async () => {
	console.log("Hello World!");
	return { message: "Hello" };
};

Writing Tests

To test my lambda function, I created a test file as lambda/tests/todoFunc/index.test.ts,

import { expect, test } from "vitest";
import { handler } from "../src/todoFunc/index";

test("todoFunc Test", () => {
	expect(handler()).resolves.toEqual({ message: "Hello" });
});

Next, in order to execute the test, add the following section to your package.json:

"scripts": {
		"test": "vitest"
	}

Running the Tests

Finally, run pnpm test, and Vitest will print this message:

stdout | tests/todoFunc/index.test.ts > todoFunc Test
Hello World!

 ✓ tests/todoFunc/index.test.ts (1)
   ✓ todoFunc Test

 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  13:15:09
   Duration  304ms (transform 204ms, setup 0ms, collect 198ms, tests 3ms, environment 0ms, prepare 36ms)


 PASS  Waiting for file changes...
       press h to show help, press q to quit

Conclusion:

Congratulations! You've successfully set up a project with Vitest, added a component, and tested it. Vitest's fast performance and seamless integration with modern development tools make it an excellent choice for testing. Continue to explore Vitest's features and customize your setup to fit your project's needs.

Thank you for reading!

Happy Learning:)

この記事をシェアする

facebook logohatena logotwitter logo

© Classmethod, Inc. All rights reserved.