Skip to content

Commit a978069

Browse files
authored
Merge pull request #62 from reynaldichernando/test-error-module
Add test error module
2 parents 3d1ddf7 + 23d2a18 commit a978069

File tree

2 files changed

+45
-3
lines changed

2 files changed

+45
-3
lines changed

src/modules/ErrorModule.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
const ERROR_BUFFER_LIMIT = 20;
1+
export const ERROR_BUFFER_LIMIT = 20;
22

3-
const errors = [];
3+
export const errors = [];
44

55
export const report = (error) => {
66
errors.push(error);
77
if (errors.length > ERROR_BUFFER_LIMIT) {
8-
errors = errors.slice(errors.length - ERROR_BUFFER_LIMIT);
8+
errors.splice(0, errors.length - ERROR_BUFFER_LIMIT)
99
}
1010
}
1111
export const showLast = () => {

tests/ErrorModule.test.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import { it, describe, expect, vi, beforeEach } from "vitest";
2+
3+
vi.spyOn(console, "log").mockImplementation(() => { });
4+
vi.spyOn(console, "error").mockImplementation(() => { });
5+
6+
let errors, report, ERROR_BUFFER_LIMIT, showLast;
7+
8+
beforeEach(async () => {
9+
vi.resetModules();
10+
const module = await import("../src/modules/ErrorModule");
11+
errors = module.errors;
12+
report = module.report;
13+
ERROR_BUFFER_LIMIT = module.ERROR_BUFFER_LIMIT;
14+
showLast = module.showLast;
15+
});
16+
17+
describe("report", () => {
18+
it("should be able to report error", () => {
19+
report("hehe")
20+
expect(errors).toHaveLength(1)
21+
})
22+
23+
it("should not exceed error buffer limit", () => {
24+
for (let i = 0; i < 100; i++) {
25+
report(`error ${i}`)
26+
}
27+
expect(errors.length).lessThanOrEqual(ERROR_BUFFER_LIMIT);
28+
})
29+
})
30+
31+
describe("showLast", () => {
32+
it("should not log error if no error exists", () => {
33+
showLast();
34+
expect(console.log).toHaveBeenCalledWith(expect.stringContaining("No errors to report"));
35+
})
36+
37+
it("should log error if error exists", () => {
38+
report("hehe")
39+
showLast();
40+
expect(console.error).toHaveBeenCalledWith(expect.stringContaining("hehe"));
41+
})
42+
})

0 commit comments

Comments
 (0)