Back to Sinon

assert.threw

docs/concepts/assertions/api/threw.md

22.1.01.5 KB
Original Source

assert.threw(spyOrSpyCall, exception);

Passes, when the fake, spy or stub threw the given exception.

The exception can be a String denoting its type, or an actual object.

When only one argument is provided, the assertion passes if spy ever threw any exception.

It's possible to assert on a dedicated spyCall: sinon.assert.threw(spy.thirdCall, exception);.

js
import * as sinon from "sinon";
const f1 = sinon.fake();

f1("apple pie");

sinon.assert.threw(f1, "TypeError");
// => Uncaught Error [AssertError]: fake did not throw exception

const f2 = sinon.fake.throws(new TypeError("not an apple pie"));

try {
  f2("apple pie");
} catch (err) {
  // not used
}

// Generates no error
sinon.assert.threw(f2, "TypeError");

Asserting on a spyCall

js
import * as sinon from "sinon";
const f1 = sinon.fake();

f1("apple pie");

// get a spyCall instance
const c1 = f1.firstCall;

sinon.assert.threw(c1, "TypeError");
// => Uncaught Error [AssertError]: fake('apple pie') at REPL4:1:1 did not throw exception

const f2 = sinon.fake.throws(new TypeError("not an apple pie"));

try {
  f2("apple pie");
} catch (err) {
  // not used
}

const c2 = f2.firstCall;

// Generates no error
sinon.assert.threw(c2, "TypeError");

Example using test framework

<<< ../../../.vitepress/tests/docs/assertions/api/threw.test.js