01 async function functionUnderTest(isOK) {
02 if (isOK) return ' OK ' ;
03 throw new Error( ' not OK ' );
04 }
Which assertion accurately tests the above code?
Show answerHide answer
Correct answer: A console.assert(await functionUnderTest(true), ' OK ' )
Explanation
Explanation:This question tests your understanding of testing asynchronous functions using console.assert() with async/await syntax. The functionUnderTest is an async function that returns 'OK' when called with true and throws an error when called with false. To test the successful path, we need to call it with true, await its resolution, and assert that the resolved value matches 'OK'. The correct syntax for console.assert() is console.assert(condition, message) – it logs an error if the condition is falsy, but does nothing if truthy.
Correct Option:
A. console.assert(await functionUnderTest(true), 'OK') –
Correct. This calls functionUnderTest(true) which resolves to 'OK'. The await keyword extracts the resolved value 'OK', which is a truthy string. Since the condition is truthy, console.assert() does nothing (passes silently). The second argument 'OK' is the message that would be logged only if the condition were falsy. This accurately tests that the function returns a truthy value when called with true.
Incorrect Options:
B. console.assert(await (functionUnderTest(true), 'not OK')) –
Incorrect. This uses the comma operator inside parentheses. The expression (functionUnderTest(true), 'not OK') evaluates both operands and returns the last one, which is the string 'not OK'. The await then resolves to 'not OK' (a truthy string), so the assertion passes, but it does not test the actual return value of functionUnderTest. This is a misleading and incorrect test.
C. console.assert(functionUnderTest(true), 'OK') –
Incorrect. This calls functionUnderTest(true) without await, so it returns a Promise object, not the resolved value. A Promise object is truthy, so the assertion passes, but it does not verify that the function resolved to 'OK'. This tests the wrong thing – it only checks that a Promise was returned, not its fulfillment value.
D. console.assert(await functionUnderTest(true), 'not OK') –
Incorrect. While the syntax is valid and the condition 'OK' is truthy, the message 'not OK' is misleading and incorrect for a passing test. The assertion passes, but the message does not accurately describe what is being tested. When the condition is truthy, the message is never displayed anyway, so this is functionally equivalent to A in terms of behavior, but the message should be descriptive of the expected outcome for clarity.
Reference:
MDN Web Docs – console.assert() method
MDN Web Docs – async/await syntax
MDN Web Docs – Promise and asynchronous functions
Salesforce Trailhead – JavaScript Essentials: Asynchronous Programming and Testing