.toThrowErrorMatchingSnapshot()

Use .toThrowErrorMatchingSnapshot to test that a function throws an error matching the most recent snapshot when it is called. For example, let's say you have a drinkFlavor function that throws whenever the flavor is 'octopus', and is coded like this:

  1. function drinkFlavor(flavor) {
  2. if (flavor == 'octopus') {
  3. throw new DisgustingFlavorError('yuck, octopus flavor');
  4. }
  5. // Do some other stuff
  6. }

The test for this function will look this way:

  1. test('throws on octopus', () => {
  2. function drinkOctopus() {
  3. drinkFlavor('octopus');
  4. }
  5. expect(drinkOctopus).toThrowErrorMatchingSnapshot();
  6. });

And it will generate the following snapshot:

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

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