src/utils/try-catch.test.ts 1.3 K raw
1
import { describe, it, expect } from "bun:test";
2
import { tryCatch } from "./try-catch";
3
4
describe("tryCatch", () => {
5
	it("should return success result for resolved promise", async () => {
6
		const result = await tryCatch(Promise.resolve("success"));
7
8
		expect(result.data).toBe("success");
9
		expect(result.error).toBeNull();
10
	});
11
12
	it("should return failure result for rejected promise", async () => {
13
		const error = new Error("test error");
14
		const result = await tryCatch(Promise.reject(error));
15
16
		expect(result.data).toBeNull();
17
		expect(result.error).toBe(error);
18
	});
19
20
	it("should handle async function that throws", async () => {
21
		const asyncFunction = async () => {
22
			throw new Error("async error");
23
		};
24
25
		const result = await tryCatch(asyncFunction());
26
27
		expect(result.data).toBeNull();
28
		expect(result.error).toBeInstanceOf(Error);
29
		expect((result.error as Error).message).toBe("async error");
30
	});
31
32
	it("should handle different data types", async () => {
33
		const objectResult = await tryCatch(
34
			Promise.resolve({ id: 1, name: "test" }),
35
		);
36
		const numberResult = await tryCatch(Promise.resolve(42));
37
		const booleanResult = await tryCatch(Promise.resolve(true));
38
39
		expect(objectResult.data).toEqual({ id: 1, name: "test" });
40
		expect(numberResult.data).toBe(42);
41
		expect(booleanResult.data).toBe(true);
42
	});
43
});