Use .toThrowErrorMatchingSnapshot to test that a function throws an error matching the most recent snapshot when it is called.

You can provide an optional hint string argument that is appended to the test name. Although Jest always appends a number at the end of a snapshot name, short descriptive hints might be more useful than numbers to differentiate multiple snapshots in a single it or test block. Jest sorts snapshots by name in the corresponding .snap file.

For example, let’s say you have a drinkFlavor function that throws whenever the flavor is 'octopus', and is coded like this:

function drinkFlavor(flavor) { if (flavor == 'octopus') { throw new DisgustingFlavorError('yuck, octopus flavor'); } // Do some other stuff }

The test for this function will look this way:

test('throws on octopus', () => { function drinkOctopus() { drinkFlavor('octopus'); } expect(drinkOctopus).toThrowErrorMatchingSnapshot(); });

And it will generate the following snapshot:

exports[`drinking flavors throws on octopus 1`] = `"yuck, octopus flavor"`;

Check out React Tree Snapshot Testing for more information on snapshot testing.