Explore core concepts of mocking and spying using Sinon in Mocha for effective unit testing, including spy behaviors, mock usage, expectation handling, and proper teardown techniques. This quiz helps reinforce best practices and clarify misconceptions for reliable test suites involving test doubles.
In a unit test, which statement correctly describes a primary use of a Sinon spy when applied to a function?
Explanation: A spy records how a function is called, tracking arguments, call counts, and context, without interfering with its actual implementation. Replacing or mocking the implementation is the domain of stubs and mocks, not spies. Spies do not block function execution and do not set or enforce a specific return value; they simply observe and record call activity.
When using Sinon mocks in a Mocha test, what is the key advantage of mocks over stubs in applying expectations?
Explanation: Mocks let you set explicit expectations, such as the number of calls and argument values, and verify these expectations during or after the test. Unlike mocks, stubs typically replace function behavior but don't enforce expectations. Mocks do not automatically restore functions — they require manual restoration — and they do track calls made, unlike what one distractor suggests.
How would you verify in a Mocha test that a spied function was called with specific arguments using Sinon?
Explanation: The spy.calledWith method directly checks if the spy observed a call with particular arguments, making it the correct approach. Overwriting the implementation is not necessary for argument inspection. Checking return values does not reflect how or with what arguments the function was called. The restore method is unrelated to call argument verification.
After creating spies and mocks with Sinon in a test suite, why is restoring or resetting them important at the end of each Mocha test?
Explanation: Restoring or resetting ensures that instrumentation on functions does not persist between tests, avoiding interference and making tests reliable. Test speed is not directly impacted by not resetting. Assertion count is not increased by restoring or resetting doubles. Running code outside the test context is unrelated.
What typically happens in a Mocha test if a Sinon mock’s expectation is not met during test execution?
Explanation: If a mock's expectation is violated, the test fails with a clear message about the unsatisfied expectation, ensuring visibility of the issue. Mocks never auto-pass unmet expectations. Skipping assertions or doubling function executions is not standard behavior in response to unmet mock expectations.