title: Jest test fails when trying to test an asynchronous function throws
body: <p>I have an asynchronous function and I want to test for both: success and failure. On success the function returns a string, on failure it throws. I'm failing miserably at testing failure. Here's my code:</p>
  
  <ul>
  <li>getKmlFileName.test.js</li>
  </ul>
  
  <p>I have disabled by commenting the code that fails and added the results in comments</p>
  
  <pre><code>    'use strict';
  
      const path = require('path');
      const fs = require('fs');
  
      const getKmlFilename = require('./getKmlFileName.js');
  
      const createGoodFolder = () =&gt; {
        const folderPath = fs.mkdtempSync('/tmp/test-getKmlFilename-');
        const fileDescriptor = fs.openSync(path.join(folderPath, 'doc.kml'), 'w');
        fs.closeSync(fileDescriptor);
        return folderPath;
      };
  
      const createEmptyFolder = () =&gt; fs.mkdtempSync('/tmp/test-getKmlFilename-');
  
      describe('/app/lib/getKmlFilename', () =&gt; {
        // Success tests
        test('Should return a KML filename', async () =&gt; {
          const result = await getKmlFilename(createGoodFolder());
          expect(result).toMatch(/\.kml$/);
        });
  
        // Failure tests
        test('Should throw if no KML files in folder', () =&gt; {
          // Expected one assertion to be called but received zero assertion calls.
          // expect.assertions(1);
  
          // expect(function).toThrow(undefined)
          // Received value must be a function, but instead "object" was found
          //return getKmlFilename(createEmptyFolder())
          // .catch(e =&gt; expect(e).toThrow());
  
          // expect(string)[.not].toMatch(expected)
          // string value must be a string.
          // Received:
          // object:
          // [Error: No valid KML file in /tmp/test-getKmlFilename-j2XxQ4]
  
          return getKmlFilename(createEmptyFolder())
            .catch(e =&gt; expect(e).toMatch('No valid KML file in'));
        });
  
        test('Should throw if no KML files in folder - try/catch version',
          async () =&gt; {
          // Expected one assertion to be called but received zero assertion calls.
          // expect.assertions(1);
  
          try {
            const result = await getKmlFilename(createEmptyFolder());
          } catch (e) {
            // Received value must be a function, but instead "object" was found
            // expect(e).toThrow();
  
            // expect(string)[.not].toMatch(expected)
            // string value must be a string.
            // Received:
            // object:
            // [Error: No valid KML file in /tmp/test-getKmlFilename-3JOUAX]
            expect(e).toMatch('No valid KML file in');
          }
        });
  
      });
  </code></pre>
  
  <p>As you can see, nothing works. I believe my tests are almost an exact copy of <a href="https://facebook.github.io/jest/docs/en/asynchronous.html#promises" rel="noreferrer">Promises</a> example for the first failure test and <a href="https://facebook.github.io/jest/docs/en/asynchronous.html#async-await" rel="noreferrer">Async/Await</a> example for the last one, however none works.</p>
  
  <p>I believe the difference with the examples from Jest documentation is that they show how to test a function <code>throw</code>s and how to test a Promise that <code>reject</code>s. But my promise rejects by throwing.</p>
  
  <p>Checking the function in the node console I get this log:</p>
  
  <pre><code>// import function
  &gt; getKml = require('./getKmlFileName.js')
  [AsyncFunction: getKmlFilename]
  // trying it with a proper folder shows we get a Promise
  &gt; getKml('/tmp/con')
  Promise {
    &lt;pending&gt;,
    domain: 
     Domain {
       domain: null,
       _events: { error: [Function: debugDomainError] },
       _eventsCount: 1,
       _maxListeners: undefined,
       members: [] } }
  // trying it with a failing folder shows it's a rejected promise which throws
  &gt; getKml('/tmp/sin')
  Promise {
    &lt;pending&gt;,
    domain: 
     Domain {
       domain: null,
       _events: { error: [Function: debugDomainError] },
       _eventsCount: 1,
       _maxListeners: undefined,
       members: [] } }
  &gt; (node:10711) UnhandledPromiseRejectionWarning: Error: No valid KML file in /tmp/sin
      at getKmlFilename (/home/flc/soft/learning/2018.06.08,jest/getKmlFileName.js:14:11)
      at &lt;anonymous&gt;
      at process._tickDomainCallback (internal/process/next_tick.js:228:7)
  (node:10711) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
  (node:10711) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
  </code></pre>
  
  <p>As you can see from the inlined comments, the function is doing what it should, however I don't know how to test this in Jest. Any help would be very much appreciated.</p>
  
  <p>I case the code here looks too convoluted, I prepared a <a href="https://github.com/fernandocanizo/learning-jest" rel="noreferrer">repository</a> which contains my misfortunes learning Jest</p>
  
  <p><strong>UPDATE 2018.06.12:</strong></p>
  
  <p>Somehow my message got scrambled and lost the first part which was the actual code I'm trying to test, my apologies for that, here it is:</p>
  
  <ul>
  <li><p>getKmlFileName.js</p>
  
  <pre><code>'use strict';
  const globby = require('globby');
  const path = require('path');
  
  const getKmlFilename = async (workDir) =&gt; {
    const pattern = path.join(workDir, '**/*.kml');
    const files = await globby(pattern);
    if (files &amp;&amp; files.length &gt; 0) {
      // Return first KML found, if there are others (improbable), ignore them
      return path.basename(files[0]);
    } else {
      throw new Error(`No valid KML file in ${workDir}`);
    }
  };
  
  module.exports = getKmlFilename;
  </code></pre></li>
  </ul>