JavaScript Testing 2 — Questions and Answers
Question 1: Which Jest method is used to mock a module's implementation for all tests in a file?
- jest.mock() (Correct answer)
- jest.spyOn()
- jest.fn()
- jest.stub()
Correct answer: jest.mock()
jest.mock() hoists the mock to the top of the file and replaces the entire module for all tests.
Question 2: What does the `--coverage` flag do when running Jest?
- Runs only covered test files
- Generates a code coverage report (Correct answer)
- Skips uncovered lines
- Increases test timeout
Correct answer: Generates a code coverage report
The --coverage flag instructs Jest to collect and report code coverage statistics for tested files.
Question 3: In Mocha, which hook runs once before all tests in a describe block?
- beforeEach
- before (Correct answer)
- afterAll
- setup
Correct answer: before
The `before` hook in Mocha runs once before all tests within its enclosing describe block.
Question 4: What is a test double in software testing?
- Running the same test twice
- An object that replaces a real dependency during testing (Correct answer)
- A test with two assertions
- A duplicate test case
Correct answer: An object that replaces a real dependency during testing
A test double is any object substituted for a real dependency — including mocks, stubs, spies, and fakes.
Question 5: Which assertion library method checks that a function throws an error in Jest?
- expect(fn).toThrow() (Correct answer)
- expect(fn).toError()
- expect(fn).throws()
- expect(fn).rejects()
Correct answer: expect(fn).toThrow()
expect(fn).toThrow() verifies that a function throws when called, optionally matching the error message or type.
Question 6: What is the purpose of `jest.clearAllMocks()` called in `afterEach`?
- Removes all mock modules
- Resets mock implementations to undefined
- Clears mock.calls, mock.instances, and mock.results between tests (Correct answer)
- Restores original implementations
Correct answer: Clears mock.calls, mock.instances, and mock.results between tests
jest.clearAllMocks() clears usage data (calls/instances/results) but keeps the mock implementation in place.
Question 7: In testing terminology, what is a 'false positive'?
- A test that passes when the code is correct
- A test that fails when the code is correct
- A test that passes when the code has a bug (Correct answer)
- A test that is skipped
Correct answer: A test that passes when the code has a bug
A false positive is a test that passes (reports green) even though the code under test contains a bug.
Which Jest method is used to mock a module's implementation for all tests in a file?