Mocks, Spies & Integration

Preview — 3 of 10 questions

What do beforeEach and afterEach do in test frameworks?

javascript
describe("User Database", () => {
  let db;
  
  beforeEach(() => {
    // Setup: runs before EACH test
    db = new Database();
    db.connect();
    console.log("Setup complete");
  });
  
  afterEach(() => {
    // Cleanup: runs after EACH test
    db.disconnect();
    console.log("Cleanup complete");
  });
  
  test("should add user", () => {
    console.log("Test 1");
    db.addUser({ name: "Alice" });
    expect(db.getUser(1).name).toBe("Alice");
  });
  
  test("should get user", () => {
    console.log("Test 2");
    db.addUser({ name: "Bob" });
    expect(db.getUser(1).name).toBe("Bob");
  });
});

// Output:
// Setup complete
// Test 1
// Cleanup complete
// Setup complete
// Test 2
// Cleanup complete
ARun before and after all tests in a suite.
BRun before and after each individual test.
CAre aliases for setUp and tearDown.
DAre only used in end-to-end tests.

How do you test an async function?

javascript
function fetchUser(id) {
  return fetch(`/api/users/${id}`).then(r => r.json());
}

test("should fetch user", () => {
  // Return the Promise to wait for it
  return fetchUser(1).then(user => {
    expect(user.name).toBe("Alice");
  });
});
ATest functions must be synchronous.
BReturn a Promise or use async/await.
CUse done callback only.
DAsync functions cannot be tested.

How do you test that a function throws an error?

javascript
function divide(a, b) {
  if (b === 0) {
    throw new Error("Cannot divide by zero");
  }
  return a / b;
}

test("should throw error when dividing by zero", () => {
  expect(() => divide(10, 0)).toThrow("Cannot divide by zero");
  expect(() => divide(10, 0)).toThrow(Error);
});
ALet the error happen naturally.
BUse expect(...).toThrow() or expect(...).rejects.toThrow().
CTry/catch around the function.
DErrors cannot be tested.

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.