Salesforce Certified JavaScript Developer Practice Questions

Salesforce Certified JavaScript Developer exam preparation

Salesforce Certified JavaScript Developer practice questions in English: 180 questions with explanations. The mock exam has 60 questions and 105 minutes.

Salesforce Certified JavaScript Developer free question 10 / 10 · Domain 7: Testing

A project uses node:test and node:assert (the variables test and assert come from those modules). validate should throw for an empty string as well, but it does not. The test below passes anyway. function validate(name) { if (name === undefined) { throw new TypeError('name is required'); } return name; } test('rejects an empty name', () => { try { validate(''); } catch (err) { assert.ok(err instanceof TypeError); } }); Which change makes the test detect the problem?

  1. Move the assert.ok call above the try statement, outside of the catch
  2. Use assert.throws(() => validate(''), TypeError) instead of try
  3. Add a finally block that calls assert.ok(true) after the try
  4. Replace the try statement with assert.doesNotThrow(() => validate(''))
Show the answer and explanation

Answer: B

Why this is correct
When validate does not throw, the catch block never runs, so the test contains no failing assertion and a synchronous test passes if it does not throw. assert.throws expects the function to throw an error, so it fails when validate returns normally.

Why the other options are wrong
"Move the assert.ok call above the try statement, outside of the catch" … Outside the catch block there is no error object to check, and the test would still pass when validate does not throw.
"Add a finally block that calls assert.ok(true) after the try" … A finally block runs whether or not an error was thrown, and assert.ok(true) cannot fail. The test would pass in every case.
"Replace the try statement with assert.doesNotThrow(() => validate(''))" … assert.doesNotThrow asserts the opposite behavior. It passes when no error is thrown, which is the current bug.

Key points
Do not put the assertion only in a catch block. Use assert.throws, or assert.rejects for promises.

Go to the Salesforce Certified JavaScript Developer practice app (10 free questions; purchase unlocks all questions)

See the full practice set