Skip to content

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

javascript

Write a basic Jest expectation.

test("adds numbers", () => {
  expect(1 + 2).toBe(3);
});

2. Mock Function

javascript

Assert a mock was called.

const fn = jest.fn();
fn("a");
expect(fn).toHaveBeenCalledWith("a");

3. Async Test

javascript

Test an async function.

test("resolves", async () => {
  await expect(Promise.resolve(1)).resolves.toBe(1);
});

4. Spy On Method

javascript

Spy on an object method.

const spy = jest.spyOn(api, "fetchUser").mockResolvedValue({ id: 1 });
await api.fetchUser(1);
expect(spy).toHaveBeenCalled();

5. Mock Module

javascript

Mock a module import.

jest.mock("./db", () => ({
  query: jest.fn().mockResolvedValue([]),
}));

6. Fake Timers

javascript

Advance 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

javascript

Use beforeEach cleanup.

beforeEach(() => {
  jest.clearAllMocks();
});

8. Snapshot Test

javascript

Match a component snapshot.

expect(render(<Button />)).toMatchSnapshot();

9. Error Throw

javascript

Expect a function to throw.

expect(() => parse("bad")).toThrow("Invalid");

10. Coverage Focus

javascript

Test branch coverage for a guard clause.

test("returns early for empty list", () => {
  expect(sum([])).toBe(0);
});