Write focused, fast unit tests for your CanxJS application components. Test controllers, services, models, and utilities in isolation.
Test your controller methods in isolation by instantiating them directly and calling their methods.
1import { describe, test, expect, beforeEach } from "bun:test";2import { UserController } from "../controllers/UserController";34describe("UserController", () => {5let controller: UserController;67beforeEach(() => {8controller = new UserController();9});1011test("index returns list of users", async () => {12const users = await controller.index();1314expect(Array.isArray(users)).toBe(true);15expect(users.length).toBeGreaterThan(0);16});1718test("show returns single user by ID", async () => {19const user = await controller.show(1);2021expect(user).toBeDefined();22expect(user.id).toBe(1);23});2425test("store creates new user", async () => {26const userData = { name: "John", email: "john@example.com" };27const user = await controller.store(userData);2829expect(user.name).toBe("John");30expect(user.email).toBe("john@example.com");31});32});
Services contain your business logic. Test them thoroughly to ensure core functionality works correctly.
1import { describe, test, expect, mock } from "bun:test";2import { AuthService } from "../services/AuthService";34describe("AuthService", () => {5test("hash password correctly", async () => {6const service = new AuthService();7const password = "mySecurePassword";89const hashed = await service.hashPassword(password);1011expect(hashed).not.toBe(password);12expect(hashed.length).toBeGreaterThan(20);13});1415test("verify password returns true for correct password", async () => {16const service = new AuthService();17const password = "mySecurePassword";18const hashed = await service.hashPassword(password);1920const isValid = await service.verifyPassword(password, hashed);2122expect(isValid).toBe(true);23});2425test("verify password returns false for wrong password", async () => {26const service = new AuthService();27const hashed = await service.hashPassword("correct");2829const isValid = await service.verifyPassword("wrong", hashed);3031expect(isValid).toBe(false);32});33});
Use Bun's built-in mock() and spyOn() to mock external dependencies.
1import { describe, test, expect, mock, spyOn } from "bun:test";2import { EmailService } from "../services/EmailService";3import { UserService } from "../services/UserService";45describe("UserService with mocks", () => {6test("sends welcome email on registration", async () => {7// Create mock8const sendEmailMock = mock(() => Promise.resolve(true));910const emailService = new EmailService();11spyOn(emailService, "send").mockImplementation(sendEmailMock);1213const userService = new UserService(emailService);14await userService.register({15name: "John",16email: "john@example.com"17});1819expect(sendEmailMock).toHaveBeenCalled();20expect(sendEmailMock).toHaveBeenCalledWith(21"john@example.com",22"Welcome to CanxJS!"23);24});25});