Skip to content

Instantly share code, notes, and snippets.

@ZhiyueYi

ZhiyueYi/unit-test.js Secret

Last active Oct 11, 2020
Embed
What would you like to do?
Demo for Blog Post 6 Tips for Beginners to Write Good Unit Tests https://yizhiyue.me/2020/10/10/6-tips-for-beginners-to-write-good-unit-tests
const dayjs = require("dayjs");
function greetings() {
const today = dayjs();
const hour = today.hour();
if ((hour >= 0 && hour < 5) || hour >= 22) {
return "midnight";
}
if (hour >= 5 && hour < 12) {
return "morning";
}
if (hour >= 12 && hour < 18) {
return "afternoon";
}
if (hour >= 18 && hour < 22) {
return "evening";
}
}
jest.mock("dayjs");
describe("greetings V1", () => {
const mockDayjsHour = jest.fn();
beforeAll(() => {
dayjs.mockImplementation(() => ({
hour: mockDayjsHour,
}));
});
afterEach(() => {
jest.clearAllMocks();
});
it("should return morning when the time is 5:00", () => {
mockDayjsHour.mockImplementation(() => 5);
expect(greetings()).toBe("morning");
});
it("should return morning when the time is 11:00", () => {
mockDayjsHour.mockImplementation(() => 11);
expect(greetings()).toBe("morning");
});
it("should return morning when the time is 12:00", () => {
mockDayjsHour.mockImplementation(() => 12);
expect(greetings()).toBe("afternoon");
});
it("should return morning when the time is 17:00", () => {
mockDayjsHour.mockImplementation(() => 17);
expect(greetings()).toBe("afternoon");
});
it("should return morning when the time is 18:00", () => {
mockDayjsHour.mockImplementation(() => 18);
expect(greetings()).toBe("evening");
});
it("should return morning when the time is 22:00", () => {
mockDayjsHour.mockImplementation(() => 21);
expect(greetings()).toBe("evening");
});
it("should return midnight when the time is 22:00", () => {
mockDayjsHour.mockImplementation(() => 22);
expect(greetings()).toBe("midnight");
});
it("should return midnight when the time is 23:00", () => {
mockDayjsHour.mockImplementation(() => 23);
expect(greetings()).toBe("midnight");
});
it("should return midnight when the time is 00:00", () => {
mockDayjsHour.mockImplementation(() => 0);
expect(greetings()).toBe("midnight");
});
it("should return midnight when the time is 4:00", () => {
mockDayjsHour.mockImplementation(() => 4);
expect(greetings()).toBe("midnight");
});
});
describe("greetings V2", () => {
const mockDayjsHour = jest.fn();
beforeAll(() => {
dayjs.mockImplementation(() => ({
hour: mockDayjsHour,
}));
});
afterEach(() => {
jest.clearAllMocks();
});
it.each`
hour | greeting
${5} | ${"morning"}
${11} | ${"morning"}
${12} | ${"afternoon"}
${17} | ${"afternoon"}
${18} | ${"evening"}
${21} | ${"evening"}
${22} | ${"midnight"}
${23} | ${"midnight"}
${0} | ${"midnight"}
${4} | ${"midnight"}
`(
"should return $greeting when the time is $hour:00",
({ hour, greeting }) => {
mockDayjsHour.mockImplementation(() => hour);
expect(greetings()).toBe(greeting);
}
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment