typesense/benchmark/test/stringifiable.test.ts
Fanis Tharropoulos fd149fd7af
feat(utils): add isStringifiable type guard function
- Add type guard to check if value has `toString` method
- Add tests for strings, numbers, booleans and objects
- Add type narrowing validation test
2025-01-03 18:31:30 +02:00

43 lines
1.2 KiB
TypeScript

import { describe, expect, it } from "vitest";
import { isStringifiable } from "../src/utils/stringifiable";
describe("isStringifiable", () => {
it("returns true for strings", () => {
expect(isStringifiable("")).toBe(true);
expect(isStringifiable("hello")).toBe(true);
});
it("returns true for numbers", () => {
expect(isStringifiable(0)).toBe(true);
expect(isStringifiable(-1)).toBe(true);
expect(isStringifiable(1.5)).toBe(true);
});
it("returns true for booleans", () => {
expect(isStringifiable(true)).toBe(true);
expect(isStringifiable(false)).toBe(true);
});
it("returns true for objects with toString method", () => {
expect(isStringifiable({})).toBe(true);
expect(isStringifiable(new Date())).toBe(true);
expect(isStringifiable(/regex/)).toBe(true);
});
it("returns false for null", () => {
expect(isStringifiable(null)).toBe(false);
});
it("returns false for undefined", () => {
expect(isStringifiable(undefined)).toBe(false);
});
it("type narrowing works", () => {
const value: unknown = "test";
if (isStringifiable(value)) {
expect(value.toString()).toBe("test");
}
});
});