Coding practice
Jest Coding Questions
10 hands-on challenges with prompts and solution sketches for Jest interview rounds.
Challenge set
10 coding questions
1. Basic Assertion
javascriptWrite a basic Jest expectation.
test("adds numbers", () => {
expect(1 + 2).toBe(3);
}); 2. Mock Function
javascriptAssert a mock was called.
const fn = jest.fn();
fn("a");
expect(fn).toHaveBeenCalledWith("a"); 3. Async Test
javascriptTest an async function.
test("resolves", async () => {
await expect(Promise.resolve(1)).resolves.toBe(1);
}); 4. Spy On Method
javascriptSpy on an object method.
const spy = jest.spyOn(api, "fetchUser").mockResolvedValue({ id: 1 });
await api.fetchUser(1);
expect(spy).toHaveBeenCalled(); 5. Mock Module
javascriptMock a module import.
jest.mock("./db", () => ({
query: jest.fn().mockResolvedValue([]),
})); 6. Fake Timers
javascriptAdvance timers in a debounce test.
jest.useFakeTimers();
const fn = jest.fn();
const debounced = debounce(fn, 300);
debounced();
jest.advanceTimersByTime(300);
expect(fn).toHaveBeenCalled(); 7. Setup Teardown
javascriptUse beforeEach cleanup.
beforeEach(() => {
jest.clearAllMocks();
}); 8. Snapshot Test
javascriptMatch a component snapshot.
expect(render(<Button />)).toMatchSnapshot(); 9. Error Throw
javascriptExpect a function to throw.
expect(() => parse("bad")).toThrow("Invalid"); 10. Coverage Focus
javascriptTest branch coverage for a guard clause.
test("returns early for empty list", () => {
expect(sum([])).toBe(0);
});