inIntelliPrompt· 10 hours ago
Write unit tests for a function
0
Prompt · v1
Write unit tests with Vitest for the function below. Cover normal cases, edge cases (empty input, invalid input, boundaries) and one test per bug you suspect. Use descriptive test names and no mocks unless needed. After the tests, list any bugs the tests would reveal. Write at most 8 focused tests and keep the whole answer under 500 words.
```ts
export function parseDuration(input: string): number {
// "1h30m" -> 5400 seconds, "45s" -> 45, "2m" -> 120
const match = input.match(/(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?/);
const [, h, m, s] = match!;
return Number(h ?? 0) * 3600 + Number(m ?? 0) * 60 + Number(s ?? 0);
}
```Best answer
Claude Haiku 5.5 · 10.2 s · 2004 tokens · temp 0.7
import { describe, it, expect } from "vitest";
import { parseDuration } from "./parseDuration";
describe("parseDuration", () => {
it("parses combined hours and minutes like '1h30m' as 5400 seconds", () => {
expect(parseDuration("1h30m")).toBe(5400);
});
it("parses single-unit inputs like '45s' and '2m' correctly", () => {
expect(parseDuration("45s")).toBe(45);
expect(parseDuration("2m")).toBe(120);
});
it("returns 0 for an empty string", () => {
expect(parseDuration("")).toBe(0);
});
it("throws on non-duration text like 'abc' instead of returning 0", () => {
expect(() => parseDuration("abc")).toThrow();
});
it("throws when a trailing number has no unit, like '1h30'", () => {
expect(() => parseDuration("1h30")).toThrow();
});
it("throws when units are out of order, like '30m1h'", () => {
expect(() => parseDuration("30m1h")).toThrow();
});
it("throws on negative values like '-5s'", () => {
expect(() => parseDuration("-5s")).toThrow();
});
it("throws on decimal values like '1.5h'", () => {
expect(() => parseDuration("1.5h")).toThrow();
});
});
Bugs the tests reveal
- Regex is not anchored.
match()finds a substring anywhere in the input, so almost any string matches."abc"returns0silently. - Invalid input silently returns 0. Because every group is optional, the regex matches the empty string on any input, so errors are never surfaced.
- Trailing numbers without units are ignored.
"1h30"returns3600, dropping the30. - Unit order is not enforced.
"30m1h"returns1800, dropping the1h. - Negative values are unsupported.
"-5s"returns0instead of an error. - Decimal values are unsupported.
"1.5h"returns0. The.5is discarded and thehis never matched, so the result is wrong without any error.
Comments (0)